Index: lams_admin/.classpath =================================================================== diff -u -r4338c54ef39ccdab47dc95d28deec40f23059633 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_admin/.classpath (.../.classpath) (revision 4338c54ef39ccdab47dc95d28deec40f23059633) +++ lams_admin/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -1,23 +1,25 @@ - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + Index: lams_admin/src/java/org/lamsfoundation/lams/admin/service/ImportService.java =================================================================== diff -u -r7acb20e485013e119c7dfd90854f123c09f147cb -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_admin/src/java/org/lamsfoundation/lams/admin/service/ImportService.java (.../ImportService.java) (revision 7acb20e485013e119c7dfd90854f123c09f147cb) +++ lams_admin/src/java/org/lamsfoundation/lams/admin/service/ImportService.java (.../ImportService.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -37,6 +37,7 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; import org.apache.struts.upload.FormFile; import org.lamsfoundation.lams.logevent.LogEvent; import org.lamsfoundation.lams.logevent.service.ILogEventService; @@ -600,7 +601,7 @@ if (cell != null) { String value; try { - cell.setCellType(Cell.CELL_TYPE_STRING); + cell.setCellType(CellType.STRING); if (cell.getStringCellValue() != null) { if (cell.getStringCellValue().trim().length() != 0) { emptyRow = false; @@ -610,7 +611,7 @@ } value = cell.getStringCellValue().trim(); } catch (Exception e) { - cell.setCellType(Cell.CELL_TYPE_NUMERIC); + cell.setCellType(CellType.NUMERIC); double d = cell.getNumericCellValue(); emptyRow = false; value = new Long(new Double(d).longValue()).toString(); @@ -625,7 +626,7 @@ private String parseStringCell(HSSFCell cell) { if (cell != null) { try { - cell.setCellType(Cell.CELL_TYPE_STRING); + cell.setCellType(CellType.STRING); if (cell.getStringCellValue() != null) { if (cell.getStringCellValue().trim().length() != 0) { emptyRow = false; @@ -636,7 +637,7 @@ // log.debug("string cell value: '"+cell.getStringCellValue().trim()+"'"); return cell.getStringCellValue().trim(); } catch (Exception e) { - cell.setCellType(Cell.CELL_TYPE_NUMERIC); + cell.setCellType(CellType.NUMERIC); double d = cell.getNumericCellValue(); emptyRow = false; // log.debug("numeric cell value: '"+d+"'"); @@ -665,7 +666,7 @@ String roleDescription = ""; if (cell != null) { try { - cell.setCellType(Cell.CELL_TYPE_STRING); + cell.setCellType(CellType.STRING); if ((cell.getStringCellValue() != null) || (cell.getStringCellValue().trim().length() != 0)) { emptyRow = false; } else { Index: lams_build/conf/standalone.xml =================================================================== diff -u -rf3204b638b1e3b4a91854b23464fa244ea6a17a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_build/conf/standalone.xml (.../standalone.xml) (revision f3204b638b1e3b4a91854b23464fa244ea6a17a1) +++ lams_build/conf/standalone.xml (.../standalone.xml) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -1,6 +1,6 @@ - + @@ -76,7 +76,7 @@ - + @@ -142,6 +142,7 @@ + @@ -167,16 +168,6 @@ - - - - - - - - @@ -237,7 +228,7 @@ - + @@ -266,16 +257,18 @@ - + @db.url.run@ MySQL utf8 true - convertToNull + CONVERT_TO_NULL false true + false + @db.timezone@ @db.location@ @@ -326,7 +319,7 @@ - + false @@ -348,19 +341,28 @@ - + - + + + - + + + - + + + + + + - + - + Index: lams_common/src/java/org/lamsfoundation/lams/integration/service/IntegrationService.java =================================================================== diff -u -r3b255feabeeae3729398d969d6ee4d76947777d3 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_common/src/java/org/lamsfoundation/lams/integration/service/IntegrationService.java (.../IntegrationService.java) (revision 3b255feabeeae3729398d969d6ee4d76947777d3) +++ lams_common/src/java/org/lamsfoundation/lams/integration/service/IntegrationService.java (.../IntegrationService.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -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; @@ -74,10 +72,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; /** @@ -778,25 +780,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 @@ -805,7 +804,7 @@ // ,,,,,, String[] userData = new String[13]; for (int k = 1; k <= 13; k++) { - String userProperty = jsonUser.getString("" + k); + String userProperty = JsonUtil.optString(jsonUser, "" + k); userData[k - 1] = userProperty; } String salt = HashUtil.salt(); @@ -829,7 +828,7 @@ group.setUsers(users); } else { - group.setNumberUsers(jsonGroup.getInt("groupSize")); + group.setNumberUsers(JsonUtil.optInt(jsonGroup, "groupSize")); } } Index: lams_common/src/java/org/lamsfoundation/lams/rest/ToolRestManager.java =================================================================== diff -u --- lams_common/src/java/org/lamsfoundation/lams/rest/ToolRestManager.java (revision 0) +++ lams_common/src/java/org/lamsfoundation/lams/rest/ToolRestManager.java (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -0,0 +1,31 @@ +/**************************************************************** + * Copyright (C) 2005 LAMS Foundation (http://lamsfoundation.org) + * ============================================================= + * License Information: http://lamsfoundation.org/licensing/lams/2.0/ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2.0 + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA + * + * http://www.gnu.org/licenses/gpl.txt + * **************************************************************** + */ + +package org.lamsfoundation.lams.rest; + +import java.io.IOException; + +import com.fasterxml.jackson.databind.node.ObjectNode; + +public interface ToolRestManager { + void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) throws IOException; +} \ No newline at end of file Index: lams_common/src/java/org/lamsfoundation/lams/util/WebUtil.java =================================================================== diff -u -r24e3879be322523d08055711ab6fa8968047782b -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_common/src/java/org/lamsfoundation/lams/util/WebUtil.java (.../WebUtil.java) (revision 24e3879be322523d08055711ab6fa8968047782b) +++ lams_common/src/java/org/lamsfoundation/lams/util/WebUtil.java (.../WebUtil.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -14,8 +14,6 @@ import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; -import org.apache.tomcat.util.json.JSONException; -import org.apache.tomcat.util.json.JSONObject; import org.lamsfoundation.lams.learning.service.ILearnerService; import org.lamsfoundation.lams.learningdesign.dto.ActivityPositionDTO; import org.lamsfoundation.lams.tool.ToolAccessMode; @@ -25,6 +23,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; + /** * helper methods useful for servlets */ @@ -369,7 +370,7 @@ } throw new IllegalArgumentException("[" + modeValue + "] is not a legal mode" + "in LAMS"); } - + /** * Get ToolAccessMode from HttpRequest parameters. Default value is AUTHOR mode. * @@ -378,7 +379,7 @@ */ public static ToolAccessMode readToolAccessModeAuthorDefaulted(HttpServletRequest request) { String modeStr = request.getParameter(AttributeNames.ATTR_MODE); - + ToolAccessMode mode; if (StringUtils.equalsIgnoreCase(modeStr, ToolAccessMode.TEACHER.toString())) { mode = ToolAccessMode.TEACHER; @@ -554,8 +555,8 @@ /** * Produces JSON object with basic user details. */ - public static JSONObject userToJSON(User user) throws JSONException { - JSONObject userJSON = new JSONObject(); + public static ObjectNode userToJSON(User user) { + ObjectNode userJSON = JsonNodeFactory.instance.objectNode(); userJSON.put("id", user.getUserId()); userJSON.put("firstName", user.getFirstName()); userJSON.put("lastName", user.getLastName()); Index: lams_gradebook/.classpath =================================================================== diff -u -r8247b17119f9b3d3c9258069313ed2510a5f0650 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_gradebook/.classpath (.../.classpath) (revision 8247b17119f9b3d3c9258069313ed2510a5f0650) +++ lams_gradebook/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -10,16 +10,18 @@ - + - + + + Index: lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookAction.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookAction.java (.../GradebookAction.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookAction.java (.../GradebookAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -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; @@ -67,6 +65,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 * @@ -212,12 +214,12 @@ List gradebookActivityDTOs = getGradebookService().getGBLessonComplete(lessonId, userId); - JSONObject resultJSON = new JSONObject(); + ObjectNode resultJSON = JsonNodeFactory.instance.objectNode(); resultJSON.put(CommonConstants.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) { @@ -227,21 +229,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(CommonConstants.ELEMENT_CELL, cellJSON); - rowsJSON.put(rowJSON); + rowJSON.set(CommonConstants.ELEMENT_CELL, cellJSON); + rowsJSON.add(rowJSON); } - resultJSON.put(CommonConstants.ELEMENT_ROWS, rowsJSON); + resultJSON.set(CommonConstants.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(); @@ -257,7 +259,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_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookMonitoringAction.java =================================================================== diff -u -rde5cc7dfd68d4a8ef5ebb5702afb4d42a5a9273a -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookMonitoringAction.java (.../GradebookMonitoringAction.java) (revision de5cc7dfd68d4a8ef5ebb5702afb4d42a5a9273a) +++ lams_gradebook/src/java/org/lamsfoundation/lams/gradebook/web/action/GradebookMonitoringAction.java (.../GradebookMonitoringAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -20,7 +20,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.gradebook.web.action; import java.io.IOException; @@ -39,8 +38,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.gradebook.service.IGradebookFullService; import org.lamsfoundation.lams.gradebook.util.GBGridView; import org.lamsfoundation.lams.gradebook.util.GradebookConstants; @@ -58,13 +55,17 @@ import org.lamsfoundation.lams.util.ExcelCell; import org.lamsfoundation.lams.util.ExcelUtil; import org.lamsfoundation.lams.util.FileUtil; +import org.lamsfoundation.lams.util.JsonUtil; 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.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * Handles the monitor interfaces for gradebook. This is where marking for an activity/lesson takes place * @@ -102,7 +103,7 @@ LessonDetailsDTO lessonDetatilsDTO = lesson.getLessonDetails(); request.setAttribute("lessonDetails", lessonDetatilsDTO); request.setAttribute("marksReleased", marksReleased); - + List weights = getGradebookService().getWeights(lesson.getLearningDesign()); if ( weights.size() > 0 ) { request.setAttribute("weights", weights); @@ -376,7 +377,7 @@ response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the organisation"); return null; } - + boolean simplified = WebUtil.readBooleanParam(request, "simplified", false); Organisation organisation = (Organisation) getUserService().findById(Organisation.class, organisationID); @@ -406,12 +407,12 @@ return null; } - + /** * Get the raw marks for display in a histogram. */ public ActionForward getMarkChartData(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException, JSONException { + HttpServletResponse response) throws IOException, ServletException { Long lessonID = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); if (!getSecurityService().isLessonMonitor(lessonID, getUser().getUserID(), @@ -421,13 +422,14 @@ } List results = getGradebookService().getMarksArray(lessonID); - - 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])); + } + response.setContentType("application/json;charset=utf-8"); response.getWriter().write(responseJSON.toString()); return null; Index: lams_learning/.classpath =================================================================== diff -u -rde5cc7dfd68d4a8ef5ebb5702afb4d42a5a9273a -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_learning/.classpath (.../.classpath) (revision de5cc7dfd68d4a8ef5ebb5702afb4d42a5a9273a) +++ lams_learning/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -10,19 +10,22 @@ - - + + + - - + + + + Index: lams_learning/src/java/org/lamsfoundation/lams/learning/kumalive/KumaliveAction.java =================================================================== diff -u -rde5cc7dfd68d4a8ef5ebb5702afb4d42a5a9273a -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_learning/src/java/org/lamsfoundation/lams/learning/kumalive/KumaliveAction.java (.../KumaliveAction.java) (revision de5cc7dfd68d4a8ef5ebb5702afb4d42a5a9273a) +++ lams_learning/src/java/org/lamsfoundation/lams/learning/kumalive/KumaliveAction.java (.../KumaliveAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -14,9 +14,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.learning.kumalive.model.Kumalive; import org.lamsfoundation.lams.learning.kumalive.model.KumaliveRubric; import org.lamsfoundation.lams.learning.kumalive.service.IKumaliveService; @@ -30,13 +27,19 @@ import org.lamsfoundation.lams.util.ExcelCell; import org.lamsfoundation.lams.util.ExcelUtil; import org.lamsfoundation.lams.util.FileUtil; +import org.lamsfoundation.lams.util.JsonUtil; 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.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; +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 Marcin Cieslak */ @@ -67,9 +70,9 @@ } List rubrics = KumaliveAction.getKumaliveService().getRubrics(organisationId); - JSONArray rubricsJSON = new JSONArray(); + ArrayNode rubricsJSON = JsonNodeFactory.instance.arrayNode(); for (KumaliveRubric rubric : rubrics) { - rubricsJSON.put(rubric.getName()); + rubricsJSON.add(rubric.getName()); } request.setAttribute("rubrics", rubricsJSON); @@ -99,7 +102,7 @@ } public ActionForward getReportOrganisationData(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, JSONException { + HttpServletResponse response) throws IOException { UserDTO userDTO = getUserDTO(); Integer currentUserId = userDTO.getUserID(); Integer organisationId = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID, false); @@ -122,15 +125,15 @@ String sortOrder = WebUtil.readStrParam(request, CommonConstants.PARAM_SORD); String sortColumn = WebUtil.readStrParam(request, CommonConstants.PARAM_SIDX, true); - JSONObject resultJSON = KumaliveAction.getKumaliveService().getReportOrganisationData(organisationId, + ObjectNode resultJSON = KumaliveAction.getKumaliveService().getReportOrganisationData(organisationId, sortColumn, !"DESC".equalsIgnoreCase(sortOrder), rowLimit, page); writeResponse(response, LamsDispatchAction.CONTENT_TYPE_TEXT_XML, LamsDispatchAction.ENCODING_UTF8, resultJSON.toString()); return null; } public ActionForward getReportKumaliveRubrics(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, JSONException { + HttpServletResponse response) throws IOException { UserDTO userDTO = getUserDTO(); Integer currentUserId = userDTO.getUserID(); Long kumaliveId = WebUtil.readLongParam(request, "kumaliveId", false); @@ -151,20 +154,20 @@ return null; } - JSONArray responseJSON = new JSONArray(); + ArrayNode responseJSON = JsonNodeFactory.instance.arrayNode(); for (KumaliveRubric rubric : kumalive.getRubrics()) { - JSONArray rubricJSON = new JSONArray(); - rubricJSON.put(rubric.getRubricId()); - rubricJSON.put(rubric.getName() == null ? "" : rubric.getName()); - responseJSON.put(rubricJSON); + ArrayNode rubricJSON = JsonNodeFactory.instance.arrayNode(); + rubricJSON.add(rubric.getRubricId()); + rubricJSON.add(rubric.getName() == null ? "" : rubric.getName()); + responseJSON.add(rubricJSON); } writeResponse(response, "text/json", LamsDispatchAction.ENCODING_UTF8, responseJSON.toString()); return null; } public ActionForward getReportKumaliveData(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, JSONException { + HttpServletResponse response) throws IOException { UserDTO userDTO = getUserDTO(); Integer currentUserId = userDTO.getUserID(); Long kumaliveId = WebUtil.readLongParam(request, "kumaliveId", false); @@ -187,15 +190,15 @@ String sortOrder = WebUtil.readStrParam(request, CommonConstants.PARAM_SORD); - JSONObject responseJSON = KumaliveAction.getKumaliveService().getReportKumaliveData(kumaliveId, + ObjectNode responseJSON = KumaliveAction.getKumaliveService().getReportKumaliveData(kumaliveId, !"DESC".equalsIgnoreCase(sortOrder)); writeResponse(response, "text/json", LamsDispatchAction.ENCODING_UTF8, responseJSON.toString()); return null; } public ActionForward getReportUserData(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, JSONException { + HttpServletResponse response) throws IOException { UserDTO userDTO = getUserDTO(); Integer currentUserId = userDTO.getUserID(); Long kumaliveId = WebUtil.readLongParam(request, "kumaliveId", false); @@ -217,25 +220,27 @@ return null; } - JSONObject responseJSON = KumaliveAction.getKumaliveService().getReportUserData(kumaliveId, userId); + ObjectNode responseJSON = KumaliveAction.getKumaliveService().getReportUserData(kumaliveId, userId); writeResponse(response, "text/json", LamsDispatchAction.ENCODING_UTF8, responseJSON.toString()); return null; } public ActionForward exportKumalives(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, JSONException { + HttpServletResponse response) throws IOException { UserDTO userDTO = getUserDTO(); Integer currentUserId = userDTO.getUserID(); Integer organisationId = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID, true); List kumaliveIds = null; if (organisationId == null) { String kumaliveIdsParam = WebUtil.readStrParam(request, "kumaliveIds", false); - JSONArray kumaliveIdsJSON = new JSONArray(kumaliveIdsParam); + + ArrayNode kumaliveIdsJSON = JsonUtil.readArray(kumaliveIdsParam); kumaliveIds = new LinkedList(); - for (int index = 0; index < kumaliveIdsJSON.length(); index++) { - kumaliveIds.add(kumaliveIdsJSON.getLong(index)); + for (JsonNode kumaliveIdJSON : kumaliveIdsJSON) { + kumaliveIds.add(kumaliveIdJSON.asLong()); } + Kumalive kumalive = KumaliveAction.getKumaliveService().getKumalive(kumaliveIds.get(0)); organisationId = kumalive.getOrganisation().getOrganisationId(); } @@ -278,7 +283,7 @@ } public ActionForward saveRubrics(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, JSONException { + HttpServletResponse response) throws IOException { UserDTO userDTO = getUserDTO(); Integer userId = userDTO.getUserID(); Integer organisationId = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID, false); @@ -296,7 +301,7 @@ return null; } - JSONArray rubricsJSON = new JSONArray(WebUtil.readStrParam(request, "rubrics")); + ArrayNode rubricsJSON = JsonUtil.readArray(WebUtil.readStrParam(request, "rubrics")); KumaliveAction.getKumaliveService().saveRubrics(organisationId, rubricsJSON); return null; Index: lams_learning/src/java/org/lamsfoundation/lams/learning/kumalive/service/KumaliveService.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_learning/src/java/org/lamsfoundation/lams/learning/kumalive/service/KumaliveService.java (.../KumaliveService.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_learning/src/java/org/lamsfoundation/lams/learning/kumalive/service/KumaliveService.java (.../KumaliveService.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -42,9 +42,6 @@ import java.util.stream.Collectors; 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.learning.kumalive.dao.IKumaliveDAO; import org.lamsfoundation.lams.learning.kumalive.model.Kumalive; import org.lamsfoundation.lams.learning.kumalive.model.KumaliveLog; @@ -61,6 +58,10 @@ import org.lamsfoundation.lams.util.FileUtil; import org.lamsfoundation.lams.util.MessageService; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + public class KumaliveService implements IKumaliveService { private static Logger logger = Logger.getLogger(KumaliveService.class); @@ -91,8 +92,8 @@ * Fetches or creates a Kumalive */ @Override - public Kumalive startKumalive(Integer organisationId, Integer userId, String name, JSONArray rubricsJSON, - boolean isTeacher) throws JSONException { + public Kumalive startKumalive(Integer organisationId, Integer userId, String name, ArrayNode rubricsJSON, + boolean isTeacher) { if (isTeacher) { securityService.isGroupMonitor(organisationId, userId, "start kumalive", true); } @@ -116,8 +117,8 @@ kumaliveDAO.insert(rubric); rubrics.add(rubric); } else { - for (Short rubricIndex = 0; rubricIndex < rubricsJSON.length(); rubricIndex++) { - String rubricName = rubricsJSON.getString(rubricIndex.intValue()); + for (Short rubricIndex = 0; rubricIndex < rubricsJSON.size(); rubricIndex++) { + String rubricName = rubricsJSON.get(rubricIndex.intValue()).asText(); KumaliveRubric rubric = new KumaliveRubric(organisation, kumalive, rubricIndex, rubricName); kumaliveDAO.insert(rubric); rubrics.add(rubric); @@ -160,11 +161,11 @@ } @Override - public void saveRubrics(Integer organisationId, JSONArray rubricsJSON) throws JSONException { + public void saveRubrics(Integer organisationId, ArrayNode rubricsJSON) { Organisation organisation = (Organisation) kumaliveDAO.find(Organisation.class, organisationId); kumaliveDAO.deleteByProperty(KumaliveRubric.class, "organisation", organisation); - for (Short rubricIndex = 0; rubricIndex < rubricsJSON.length(); rubricIndex++) { - String name = rubricsJSON.getString(rubricIndex.intValue()); + for (Short rubricIndex = 0; rubricIndex < rubricsJSON.size(); rubricIndex++) { + String name = rubricsJSON.get(rubricIndex.intValue()).asText(); KumaliveRubric rubric = new KumaliveRubric(organisation, null, rubricIndex, name); kumaliveDAO.insert(rubric); } @@ -174,8 +175,8 @@ * Gets Kumalives for the given organisation packed into jqGrid JSON format */ @Override - public JSONObject getReportOrganisationData(Integer organisationId, String sortColumn, boolean isAscending, - int rowLimit, int page) throws JSONException { + public ObjectNode getReportOrganisationData(Integer organisationId, String sortColumn, boolean isAscending, + int rowLimit, int page) { List kumalives = kumaliveDAO.findKumalives(organisationId, sortColumn, isAscending); // paging @@ -194,27 +195,27 @@ } } - JSONObject resultJSON = new JSONObject(); + ObjectNode resultJSON = JsonNodeFactory.instance.objectNode(); resultJSON.put(CommonConstants.ELEMENT_PAGE, page); resultJSON.put(CommonConstants.ELEMENT_TOTAL, totalPages); resultJSON.put(CommonConstants.ELEMENT_RECORDS, kumalives.size()); - JSONArray rowsJSON = new JSONArray(); + ArrayNode rowsJSON = JsonNodeFactory.instance.arrayNode(); // IDs are arbitrary, so generate order starting from 1 int order = (page - 1) * rowLimit + (isAscending ? 1 : kumalives.size()); for (Kumalive kumalive : kumalives) { - JSONObject rowJSON = new JSONObject(); + ObjectNode rowJSON = JsonNodeFactory.instance.objectNode(); rowJSON.put(CommonConstants.ELEMENT_ID, kumalive.getKumaliveId()); - JSONArray cellJSON = new JSONArray(); - cellJSON.put(order); - cellJSON.put(kumalive.getName()); + ArrayNode cellJSON = JsonNodeFactory.instance.arrayNode(); + cellJSON.add(order); + cellJSON.add(kumalive.getName()); - rowJSON.put(CommonConstants.ELEMENT_CELL, cellJSON); - rowsJSON.put(rowJSON); + rowJSON.set(CommonConstants.ELEMENT_CELL, cellJSON); + rowsJSON.add(rowJSON); if (isAscending) { order++; @@ -223,7 +224,7 @@ } } - resultJSON.put(CommonConstants.ELEMENT_ROWS, rowsJSON); + resultJSON.set(CommonConstants.ELEMENT_ROWS, rowsJSON); return resultJSON; } @@ -232,7 +233,7 @@ * Gets learners who answered to question in the given Kumalive, packed into jqGrid JSON format */ @Override - public JSONObject getReportKumaliveData(Long kumaliveId, boolean isAscending) throws JSONException { + public ObjectNode getReportKumaliveData(Long kumaliveId, boolean isAscending) { Kumalive kumalive = getKumalive(kumaliveId); List rubrics = new LinkedList(); for (KumaliveRubric rubric : kumalive.getRubrics()) { @@ -245,17 +246,17 @@ Collectors.groupingBy(score -> score.getRubric().getRubricId(), Collectors.mapping(KumaliveScore::getScore, Collectors.toList())))); - JSONObject resultJSON = new JSONObject(); + ObjectNode resultJSON = JsonNodeFactory.instance.objectNode(); resultJSON.put(CommonConstants.ELEMENT_RECORDS, scores.size()); - JSONArray rowsJSON = new JSONArray(); + ArrayNode rowsJSON = JsonNodeFactory.instance.arrayNode(); for (Entry>> userEntry : scores.entrySet()) { - JSONObject rowJSON = new JSONObject(); + ObjectNode rowJSON = JsonNodeFactory.instance.objectNode(); User user = userEntry.getKey(); rowJSON.put(CommonConstants.ELEMENT_ID, user.getUserId()); - JSONArray cellJSON = new JSONArray(); - cellJSON.put(user.getFirstName() + " " + user.getLastName()); + ArrayNode cellJSON = JsonNodeFactory.instance.arrayNode(); + cellJSON.add(user.getFirstName() + " " + user.getLastName()); // calculate average of scores for the given rubric for (Long rubric : rubrics) { Double score = null; @@ -270,14 +271,14 @@ } } // format nicely - cellJSON.put(score == null ? "" : DECIMAL_FORMAT.format(score / attempts.size())); + cellJSON.add(score == null ? "" : DECIMAL_FORMAT.format(score / attempts.size())); } - rowJSON.put(CommonConstants.ELEMENT_CELL, cellJSON); - rowsJSON.put(rowJSON); + rowJSON.set(CommonConstants.ELEMENT_CELL, cellJSON); + rowsJSON.add(rowJSON); } - resultJSON.put(CommonConstants.ELEMENT_ROWS, rowsJSON); + resultJSON.set(CommonConstants.ELEMENT_ROWS, rowsJSON); return resultJSON; } @@ -286,7 +287,7 @@ * Gets scores for the given Kumalive and learner, packed into jqGrid JSON format */ @Override - public JSONObject getReportUserData(Long kumaliveId, Integer userId) throws JSONException { + public ObjectNode getReportUserData(Long kumaliveId, Integer userId) { Kumalive kumalive = getKumalive(kumaliveId); List rubrics = new LinkedList(); for (KumaliveRubric rubric : kumalive.getRubrics()) { @@ -298,29 +299,29 @@ .collect(Collectors.groupingBy(KumaliveScore::getBatch, LinkedHashMap::new, Collectors.toMap(score -> score.getRubric().getRubricId(), KumaliveScore::getScore))); - JSONObject resultJSON = new JSONObject(); + ObjectNode resultJSON = JsonNodeFactory.instance.objectNode(); resultJSON.put(CommonConstants.ELEMENT_RECORDS, scores.size()); - JSONArray rowsJSON = new JSONArray(); + ArrayNode rowsJSON = JsonNodeFactory.instance.arrayNode(); // just normal ordering of questions short order = 1; for (Entry> batchEntry : scores.entrySet()) { - JSONObject rowJSON = new JSONObject(); + ObjectNode rowJSON = JsonNodeFactory.instance.objectNode(); rowJSON.put(CommonConstants.ELEMENT_ID, order); - JSONArray cellJSON = new JSONArray(); - cellJSON.put(order); + ArrayNode cellJSON = JsonNodeFactory.instance.arrayNode(); + cellJSON.add(order); order++; for (Long rubric : rubrics) { Short score = batchEntry.getValue().get(rubric); - cellJSON.put(score == null ? "" : score); + cellJSON.add(score == null ? "" : score.toString()); } - rowJSON.put(CommonConstants.ELEMENT_CELL, cellJSON); - rowsJSON.put(rowJSON); + rowJSON.set(CommonConstants.ELEMENT_CELL, cellJSON); + rowsJSON.add(rowJSON); } - resultJSON.put(CommonConstants.ELEMENT_ROWS, rowsJSON); + resultJSON.set(CommonConstants.ELEMENT_ROWS, rowsJSON); return resultJSON; } @@ -552,7 +553,7 @@ * Creates a poll */ @Override - public KumalivePoll startPoll(Long kumaliveId, String name, JSONArray answersJSON) throws JSONException { + public KumalivePoll startPoll(Long kumaliveId, String name, ArrayNode answersJSON) { Kumalive kumalive = getKumalive(kumaliveId); if (kumalive == null) { return null; @@ -561,8 +562,8 @@ kumaliveDAO.insert(poll); Set answers = new LinkedHashSet<>(); - for (Short answerIndex = 0; answerIndex < answersJSON.length(); answerIndex++) { - String answerName = answersJSON.getString(answerIndex.intValue()); + for (Short answerIndex = 0; answerIndex < answersJSON.size(); answerIndex++) { + String answerName = answersJSON.get(answerIndex.intValue()).asText(); KumalivePollAnswer answer = new KumalivePollAnswer(poll, answerIndex, answerName); kumaliveDAO.insert(answer); answers.add(answer); @@ -610,7 +611,7 @@ * Finishes a poll, i.e. prevents learners from voting */ @Override - public void finishPoll(Long pollId) throws JSONException { + public void finishPoll(Long pollId) { KumalivePoll poll = (KumalivePoll) kumaliveDAO.find(KumalivePoll.class, pollId); if (poll.getFinishDate() != null) { logger.warn("Trying to finish poll " + pollId + " which is already finished"); Index: lams_learning/src/java/org/lamsfoundation/lams/learning/web/action/LearnerAction.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_learning/src/java/org/lamsfoundation/lams/learning/web/action/LearnerAction.java (.../LearnerAction.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_learning/src/java/org/lamsfoundation/lams/learning/web/action/LearnerAction.java (.../LearnerAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -39,8 +39,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.gradebook.service.IGradebookService; import org.lamsfoundation.lams.learning.presence.PresenceWebsocketServer; import org.lamsfoundation.lams.learning.service.ILearnerFullService; @@ -68,6 +66,9 @@ import org.lamsfoundation.lams.web.session.SessionManager; import org.lamsfoundation.lams.web.util.AttributeNames; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * *

@@ -212,8 +213,8 @@ // make a copy of attempted and completed activities Date archiveDate = new Date(); LearnerProgress learnerProgress = learnerService.getProgress(userID, lessonID); - Map attemptedActivities = new HashMap(learnerProgress.getAttemptedActivities()); - Map completedActivities = new HashMap(); + Map attemptedActivities = new HashMap<>(learnerProgress.getAttemptedActivities()); + Map completedActivities = new HashMap<>(); for (Entry entry : learnerProgress.getCompletedActivities().entrySet()) { CompletedActivityProgressArchive activityArchive = new CompletedActivityProgressArchive(learnerProgress, entry.getKey(), entry.getValue().getStartDate(), entry.getValue().getFinishDate()); @@ -250,7 +251,7 @@ */ @SuppressWarnings("unchecked") public ActionForward getLearnerProgress(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { Integer learnerId = WebUtil.readIntParam(request, AttributeNames.PARAM_USER_ID, true); Integer monitorId = null; HttpSession ss = SessionManager.getSession(); @@ -264,7 +265,7 @@ monitorId = userId; } - JSONObject responseJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); Long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID, true); if (lessonId == null) { // depending on when this is called, there may only be a toolSessionId known, not the lessonId. @@ -274,7 +275,7 @@ lessonId = toolSession.getLesson().getLessonId(); } - responseJSON.put("messages", getProgressBarMessages()); + responseJSON.set("messages", getProgressBarMessages()); ILearnerFullService learnerService = LearnerServiceProxy.getLearnerService(getServlet().getServletContext()); Object[] ret = learnerService.getStructuredActivityURLs(learnerId, lessonId); @@ -283,18 +284,18 @@ return null; } - responseJSON.put("currentActivityId", ret[1]); - responseJSON.put("isPreview", ret[2]); + responseJSON.put("currentActivityId", (Long) ret[1]); + responseJSON.put("isPreview", (boolean) ret[2]); for (ActivityURL activity : (List) ret[0]) { if (activity.getFloating()) { // these are support activities for (ActivityURL childActivity : activity.getChildActivities()) { - responseJSON.append("support", - activityProgressToJSON(childActivity, null, lessonId, learnerId, monitorId)); + responseJSON.withArray("support") + .add(activityProgressToJSON(childActivity, null, lessonId, learnerId, monitorId)); } } else { - responseJSON.append("activities", - activityProgressToJSON(activity, (Long) ret[1], lessonId, learnerId, monitorId)); + responseJSON.withArray("activities") + .add(activityProgressToJSON(activity, (Long) ret[1], lessonId, learnerId, monitorId)); } } @@ -356,9 +357,9 @@ /** * Converts an activity in learner progress to a JSON object. */ - private JSONObject activityProgressToJSON(ActivityURL activity, Long currentActivityId, Long lessonId, - Integer learnerId, Integer monitorId) throws JSONException, IOException { - JSONObject activityJSON = new JSONObject(); + private ObjectNode activityProgressToJSON(ActivityURL activity, Long currentActivityId, Long lessonId, + Integer learnerId, Integer monitorId) throws IOException { + ObjectNode activityJSON = JsonNodeFactory.instance.objectNode(); activityJSON.put("id", activity.getActivityId()); activityJSON.put("name", activity.getTitle()); activityJSON.put("status", activity.getActivityId().equals(currentActivityId) ? 0 : activity.getStatus()); @@ -397,16 +398,16 @@ if (activity.getChildActivities() != null) { for (ActivityURL childActivity : activity.getChildActivities()) { - activityJSON.append("childActivities", - activityProgressToJSON(childActivity, currentActivityId, lessonId, learnerId, monitorId)); + activityJSON.withArray("childActivities") + .add(activityProgressToJSON(childActivity, currentActivityId, lessonId, learnerId, monitorId)); } } return activityJSON; } - private JSONObject getProgressBarMessages() throws JSONException { - JSONObject progressBarMessages = new JSONObject(); + private ObjectNode getProgressBarMessages() { + ObjectNode progressBarMessages = JsonNodeFactory.instance.objectNode(); MessageService messageService = LearnerServiceProxy .getMonitoringMessageService(getServlet().getServletContext()); for (String key : MONITOR_MESSAGE_KEYS) { @@ -425,9 +426,9 @@ * Gets the lesson details based on lesson id or the current tool session */ public ActionForward getLessonDetails(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { - JSONObject responseJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); Lesson lesson = null; Long lessonID = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID, true); Index: lams_monitoring/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_monitoring/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_monitoring/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -9,13 +9,15 @@ - - - + + + + + Index: lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/EmailNotificationsAction.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/EmailNotificationsAction.java (.../EmailNotificationsAction.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/EmailNotificationsAction.java (.../EmailNotificationsAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -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.events.EmailNotificationArchive; import org.lamsfoundation.lams.events.IEventNotificationService; import org.lamsfoundation.lams.index.IndexLessonBean; @@ -91,6 +88,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; + /** *

* Responsible for "Email notification" functionality. @@ -133,9 +134,8 @@ ILearnerService learnerService = MonitoringServiceProxy.getLearnerService(getServlet().getServletContext()); Lesson lesson = learnerService.getLesson(lessonId); if (!lesson.getEnableLessonNotifications()) { - getLogEventService().logEvent(LogEvent.TYPE_NOTIFICATION, getCurrentUser().getUserID(), null, - lessonId, null, - "Attempted to send notification when notifications are disabled in lesson " + lessonId); + getLogEventService().logEvent(LogEvent.TYPE_NOTIFICATION, getCurrentUser().getUserID(), null, lessonId, + null, "Attempted to send notification when notifications are disabled in lesson " + lessonId); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Notifications are disabled in the lesson"); return null; } @@ -165,18 +165,18 @@ // getting the organisation Organisation org = monitoringService.getOrganisation(orgId); - boolean isGroupMonitor = getSecurityService().hasOrgRole(orgId, getCurrentUser().getUserID(), + boolean isGroupMonitor = getSecurityService().hasOrgRole(orgId, getCurrentUser().getUserID(), new String[] { Role.GROUP_MANAGER }, "show course email notifications", false); Integer userRole = isGroupMonitor ? Role.ROLE_GROUP_MANAGER : Role.ROLE_MONITOR; - Map staffMap = getLessonService().getLessonsByOrgAndUserWithCompletedFlag(getCurrentUser().getUserID(), orgId, - userRole); + Map staffMap = getLessonService() + .getLessonsByOrgAndUserWithCompletedFlag(getCurrentUser().getUserID(), orgId, userRole); // Already sorted, just double check that it does not contain finished or removed lessons // This call should not be returning REMOVED lessons anyway so test for finished ones. ArrayList lessons = new ArrayList(staffMap.size()); - for (IndexLessonBean lesson : (Collection) staffMap.values()) { + for (IndexLessonBean lesson : staffMap.values()) { if (!Lesson.FINISHED_STATE.equals(lesson.getState())) { - lessons.add(lesson); + lessons.add(lesson); } } @@ -196,7 +196,7 @@ HttpServletResponse response) throws IOException, ServletException, SchedulerException { getUserManagementService(); Scheduler scheduler = getScheduler(); - TreeSet scheduleList = new TreeSet(); + TreeSet scheduleList = new TreeSet<>(); Long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID, true); boolean isLessonNotifications = (lessonId != null); Integer organisationId = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID, true); @@ -292,7 +292,7 @@ } public ActionForward getArchivedRecipients(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { IMonitoringFullService monitoringService = MonitoringServiceProxy .getMonitoringService(getServlet().getServletContext()); @@ -326,25 +326,25 @@ (page - 1) * rowLimit); // build JSON which is understood by jqGrid - JSONObject responseJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); responseJSON.put(CommonConstants.ELEMENT_PAGE, page); responseJSON.put(CommonConstants.ELEMENT_TOTAL, ((notification.getRecipients().size() - 1) / rowLimit) + 1); responseJSON.put(CommonConstants.ELEMENT_RECORDS, recipients.size()); - JSONArray rowsJSON = new JSONArray(); + ArrayNode rowsJSON = JsonNodeFactory.instance.arrayNode(); for (User recipient : recipients) { - JSONObject rowJSON = new JSONObject(); + ObjectNode rowJSON = JsonNodeFactory.instance.objectNode(); rowJSON.put(CommonConstants.ELEMENT_ID, recipient.getUserId()); - JSONArray cellJSON = new JSONArray(); - cellJSON.put(new StringBuilder(recipient.getLastName()).append(", ").append(recipient.getFirstName()) + ArrayNode cellJSON = JsonNodeFactory.instance.arrayNode(); + cellJSON.add(new StringBuilder(recipient.getLastName()).append(", ").append(recipient.getFirstName()) .append(" [").append(recipient.getLogin()).append("]").toString()); - rowJSON.put(CommonConstants.ELEMENT_CELL, cellJSON); - rowsJSON.put(rowJSON); + rowJSON.set(CommonConstants.ELEMENT_CELL, cellJSON); + rowsJSON.add(rowJSON); } - responseJSON.put(CommonConstants.ELEMENT_ROWS, rowsJSON); + responseJSON.set(CommonConstants.ELEMENT_ROWS, rowsJSON); writeResponse(response, "text/json", LamsDispatchAction.ENCODING_UTF8, responseJSON.toString()); return null; } @@ -355,7 +355,7 @@ * @throws JSONException */ public ActionForward deleteNotification(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException, SchedulerException, JSONException { + HttpServletResponse response) throws IOException, ServletException, SchedulerException { String inputTriggerName = WebUtil.readStrParam(request, "triggerName"); Long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID, true); @@ -368,7 +368,7 @@ getUserManagementService(); Scheduler scheduler = getScheduler(); - JSONObject jsonObject = new JSONObject(); + ObjectNode jsonObject = JsonNodeFactory.instance.objectNode(); String error = null; try { @@ -397,8 +397,7 @@ JobDetail jobDetail = scheduler.getJobDetail(trigger.getJobKey()); JobDataMap jobDataMap = jobDetail.getJobDataMap(); - getLogEventService().logEvent(LogEvent.TYPE_NOTIFICATION, - userId, null, lessonId, null, + getLogEventService().logEvent(LogEvent.TYPE_NOTIFICATION, userId, null, lessonId, null, "Deleting unsent scheduled notification " + jobKey + " " + jobDataMap.getString("emailBody")); @@ -471,8 +470,9 @@ * Method called via Ajax. It either emails selected users or schedules these emails to be sent on specified date. */ public ActionForward emailUsers(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException, JSONException { - JSONObject JSONObject = new JSONObject(); + HttpServletResponse response) throws IOException, ServletException { + + ObjectNode ObjectNode = JsonNodeFactory.instance.objectNode(); IMonitoringFullService monitoringService = MonitoringServiceProxy .getMonitoringService(getServlet().getServletContext()); @@ -500,7 +500,7 @@ WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID, true), WebUtil.readIntParam(request, "searchType", true), emailBody, userIdInts); - JSONObject.put("isSuccessfullySent", isSuccessfullySent); + ObjectNode.put("isSuccessfullySent", isSuccessfullySent); //prepare data for audit log scheduleDateStr = "now"; @@ -532,7 +532,7 @@ // start the scheduling job Scheduler scheduler = getScheduler(); scheduler.scheduleJob(emailScheduleMessageJob, startLessonTrigger); - JSONObject.put("isSuccessfullyScheduled", true); + ObjectNode.put("isSuccessfullyScheduled", true); //prepare data for audit log scheduleDateStr = "on " + scheduleDate; @@ -554,22 +554,21 @@ } //audit log - getLogEventService().logEvent(LogEvent.TYPE_NOTIFICATION, getCurrentUser().getUserID(), null, - null, null, + getLogEventService().logEvent(LogEvent.TYPE_NOTIFICATION, getCurrentUser().getUserID(), null, null, null, "User " + getCurrentUser().getLogin() + " set a notification " + emailClauseStr + " " + scheduleDateStr + " with the following notice: " + emailBody); response.setContentType("application/json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(ObjectNode); return null; } /** * Refreshes user list. */ public ActionForward getUsers(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException, JSONException { - Map map = new HashMap(); + HttpServletResponse response) throws IOException, ServletException { + Map map = new HashMap<>(); copySearchParametersFromRequestToMap(request, map); Long lessonId = (Long) map.get(AttributeNames.PARAM_LESSON_ID); Integer orgId = (Integer) map.get(AttributeNames.PARAM_ORGANISATION_ID); @@ -598,28 +597,26 @@ Collection users = monitoringService.getUsersByEmailNotificationSearchType(searchType, lessonId, lessonIds, activityId, xDaystoFinish, orgId); - JSONArray cellarray = new JSONArray(); + ArrayNode cellarray = JsonNodeFactory.instance.arrayNode(); - JSONObject responcedata = new JSONObject(); - responcedata.put("total", "" + users.size()); - responcedata.put("page", "" + 1); - responcedata.put("records", "" + users.size()); + ObjectNode responseDate = JsonNodeFactory.instance.objectNode(); + responseDate.put("total", "" + users.size()); + responseDate.put("page", "" + 1); + responseDate.put("records", "" + users.size()); - // data is going into a jquery UI table that doesn't need to it be escaped. LDEV-4514 for (User user : users) { - JSONArray cell = new JSONArray(); - cell.put(new StringBuilder(user.getLastName()).append(", ") - .append(user.getFirstName()).append(" (") + ArrayNode cell = JsonNodeFactory.instance.arrayNode(); + cell.add(new StringBuilder(user.getLastName()).append(", ").append(user.getFirstName()).append(" (") .append(user.getLogin()).append(")").toString()); - JSONObject cellobj = new JSONObject(); + ObjectNode cellobj = JsonNodeFactory.instance.objectNode(); cellobj.put("id", "" + user.getUserId()); - cellobj.put("cell", cell); - cellarray.put(cellobj); + cellobj.set("cell", cell); + cellarray.add(cellobj); } - responcedata.put("rows", cellarray); + responseDate.set("rows", cellarray); response.setContentType("application/json;charset=utf-8"); - response.getWriter().print(new String(responcedata.toString())); + response.getWriter().print(new String(responseDate.toString())); return null; } Index: lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/EmailProgressAction.java =================================================================== diff -u -r4338c54ef39ccdab47dc95d28deec40f23059633 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/EmailProgressAction.java (.../EmailProgressAction.java) (revision 4338c54ef39ccdab47dc95d28deec40f23059633) +++ lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/EmailProgressAction.java (.../EmailProgressAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -20,7 +20,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.monitoring.web; import java.io.IOException; @@ -39,9 +38,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.events.IEventNotificationService; import org.lamsfoundation.lams.monitoring.quartz.job.EmailProgressMessageJob; import org.lamsfoundation.lams.monitoring.service.IMonitoringFullService; @@ -64,6 +60,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; + /** * Responsible for "Email Progress" functionality. */ @@ -86,11 +86,11 @@ /** * Gets learners or monitors of the lesson and organisation containing it. - * + * * @throws SchedulerException */ public ActionForward getEmailProgressDates(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, JSONException, SchedulerException { + HttpServletResponse response) throws IOException, SchedulerException { Long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); if (!getSecurityService().isLessonMonitor(lessonId, getCurrentUser().getUserID(), "get class members", false)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); @@ -100,13 +100,13 @@ HttpSession ss = SessionManager.getSession(); UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); - JSONObject responseJSON = new JSONObject(); - JSONArray datesJSON = new JSONArray(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); + ArrayNode datesJSON = JsonNodeFactory.instance.arrayNode(); // find all the current dates set up to send the emails Scheduler scheduler = getScheduler(); String triggerPrefix = getTriggerPrefix(lessonId); - SortedSet currentDatesSet = new TreeSet(); + SortedSet currentDatesSet = new TreeSet<>(); Set triggerKeys = scheduler .getTriggerKeys(GroupMatcher.triggerGroupEquals(Scheduler.DEFAULT_GROUP)); for (TriggerKey triggerKey : triggerKeys) { @@ -128,24 +128,24 @@ } for (Date date : currentDatesSet) { - datesJSON.put(createDateJSON(request.getLocale(), user, date, null)); + datesJSON.add(createDateJSON(request.getLocale(), user, date, null)); } - responseJSON.put("dates", datesJSON); + responseJSON.set("dates", datesJSON); response.setContentType("application/json;charset=utf-8"); response.getWriter().write(responseJSON.toString()); return null; } - private JSONObject createDateJSON(Locale locale, UserDTO user, Date date, String result) throws JSONException { - JSONObject dateJSON = new JSONObject(); + private ObjectNode createDateJSON(Locale locale, UserDTO user, Date date, String result) { + ObjectNode dateJSON = JsonNodeFactory.instance.objectNode(); if (result != null) { dateJSON.put("result", result); } if (date != null) { dateJSON.put("id", date.getTime()); dateJSON.put("ms", date.getTime()); - dateJSON.put("date", DateUtil.convertToStringForJSON(date, locale) ); + dateJSON.put("date", DateUtil.convertToStringForJSON(date, locale)); } return dateJSON; } @@ -168,7 +168,7 @@ * Add or remove a date for the email progress */ public ActionForward updateEmailProgressDate(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, getCurrentUser().getUserID(), "get class members", false)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); @@ -178,20 +178,20 @@ HttpSession ss = SessionManager.getSession(); UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); - // as we are using ms since UTC 0 calculated on the client, this will be correctly set up as server date + // as we are using ms since UTC 0 calculated on the client, this will be correctly set up as server date // and does not need changing (assuming the user's LAMS timezone matches the user's computer timezone). long dateId = WebUtil.readLongParam(request, "id"); - Date newDate = new Date(dateId); + Date newDate = new Date(dateId); boolean add = WebUtil.readBooleanParam(request, "add"); // calculate scheduleDate String scheduledTriggerName = getTriggerName(lessonId, newDate); - JSONObject dateJSON = null; + ObjectNode dateJSON = null; try { Scheduler scheduler = getScheduler(); - Set triggerKeys = scheduler.getTriggerKeys(GroupMatcher - .triggerGroupEquals(Scheduler.DEFAULT_GROUP)); + Set triggerKeys = scheduler + .getTriggerKeys(GroupMatcher.triggerGroupEquals(Scheduler.DEFAULT_GROUP)); Trigger trigger = null; for (TriggerKey triggerKey : triggerKeys) { @@ -200,15 +200,14 @@ break; } } - + if (add) { if (trigger == null) { - String desc = new StringBuilder("Send progress email. Lesson ") - .append(lessonId).append(" on ").append(newDate).toString(); + String desc = new StringBuilder("Send progress email. Lesson ").append(lessonId).append(" on ") + .append(newDate).toString(); // build job detail based on the bean class JobDetail EmailProgressMessageJob = JobBuilder.newJob(EmailProgressMessageJob.class) - .withIdentity(getJobName(lessonId, newDate)) - .withDescription(desc) + .withIdentity(getJobName(lessonId, newDate)).withDescription(desc) .usingJobData(AttributeNames.PARAM_LESSON_ID, lessonId).build(); // create customized triggers @@ -244,7 +243,7 @@ } public ActionForward sendLessonProgressEmail(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException, JSONException { + HttpServletResponse response) throws IOException, ServletException { Long lessonId = WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID); Integer monitorUserId = getCurrentUser().getUserID(); @@ -261,15 +260,15 @@ if (getEventNotificationService().sendMessage(null, monitorUserId, IEventNotificationService.DELIVERY_METHOD_MAIL, parts[0], parts[1], true)) { sent = 1; - } + } } catch (InvalidParameterException ipe) { error = ipe.getMessage(); } catch (Exception e) { error = e.getMessage(); } - JSONObject responseJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); responseJSON.put("sent", sent); if (error != null) { responseJSON.put("error", error); Index: lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/GroupingAJAXAction.java =================================================================== diff -u -r4338c54ef39ccdab47dc95d28deec40f23059633 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/GroupingAJAXAction.java (.../GroupingAJAXAction.java) (revision 4338c54ef39ccdab47dc95d28deec40f23059633) +++ lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/GroupingAJAXAction.java (.../GroupingAJAXAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -43,8 +43,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.learningdesign.Activity; import org.lamsfoundation.lams.learningdesign.Group; import org.lamsfoundation.lams.learningdesign.GroupComparator; @@ -69,6 +67,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; + /** * The action servlet that provides the support for the *

    @@ -91,15 +92,14 @@ public static final String PARAM_USED_FOR_BRANCHING = "usedForBranching"; public static final String PARAM_VIEW_MODE = "viewMode"; public static final String GROUPS = "groups"; - + private static ISecurityService securityService; /** * Start the process of doing the chosen grouping * * Input parameters: activityID */ - @SuppressWarnings("unchecked") public ActionForward startGrouping(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { @@ -152,13 +152,13 @@ return mapping.findForward(GroupingAJAXAction.CHOSEN_GROUPING_SCREEN); } - SortedSet groups = new TreeSet(new GroupComparator()); + SortedSet groups = new TreeSet<>(new GroupComparator()); groups.addAll(grouping.getGroups()); // sort users with first, then last name, then login Comparator userComparator = new FirstNameAlphabeticComparator(); for (Group group : groups) { - Set sortedUsers = new TreeSet(userComparator); + Set sortedUsers = new TreeSet<>(userComparator); sortedUsers.addAll(group.getUsers()); group.setUsers(sortedUsers); } @@ -211,9 +211,9 @@ * Moves users between groups, removing them from previous group and creating a new one, if needed. */ public ActionForward addMembers(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { response.setContentType("application/json;charset=utf-8"); - JSONObject responseJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); boolean result = true; Long activityID = WebUtil.readLongParam(request, AttributeNames.PARAM_ACTIVITY_ID); @@ -296,12 +296,12 @@ response.getWriter().write(responseJSON.toString()); return null; } - + /** * Stores lesson grouping as a course grouping. */ public ActionForward saveAsCourseGrouping(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { IMonitoringFullService monitoringService = MonitoringServiceProxy .getMonitoringService(getServlet().getServletContext()); IUserManagementService userManagementService = MonitoringServiceProxy @@ -310,7 +310,7 @@ Integer userId = ((UserDTO) ss.getAttribute(AttributeNames.USER)).getUserID(); Integer organisationId = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID); String newGroupingName = request.getParameter("name"); - + // check if user is allowed to view and edit groupings if (!getSecurityService().hasOrgRole(organisationId, userId, new String[] { Role.GROUP_ADMIN, Role.GROUP_MANAGER, Role.MONITOR, Role.AUTHOR }, @@ -325,12 +325,12 @@ : ((GroupingActivity) activity).getCreateGrouping(); // iterate over groups - List orgGroups = new LinkedList(); + List orgGroups = new LinkedList<>(); for (Group group : grouping.getGroups()) { OrganisationGroup orgGroup = new OrganisationGroup(); //groupId and GroupingId will be set during userManagementService.saveOrganisationGrouping() call orgGroup.setName(group.getGroupName()); - HashSet users = new HashSet(); + HashSet users = new HashSet<>(); users.addAll(group.getUsers()); orgGroup.setUsers(users); @@ -344,11 +344,11 @@ userManagementService.saveOrganisationGrouping(orgGrouping, orgGroups); response.setContentType("application/json;charset=utf-8"); - JSONObject responseJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); responseJSON.put("result", true); response.getWriter().write(responseJSON.toString()); return null; - } + } /** * Renames the group. @@ -367,26 +367,29 @@ } return null; } - + /** - * Checks if a course grouping name is unique inside of this organisation and thus whether the new group can be named using it + * Checks if a course grouping name is unique inside of this organisation and thus whether the new group can be + * named using it */ + @SuppressWarnings("unchecked") public ActionForward checkGroupingNameUnique(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { - IUserManagementService userManagementService = MonitoringServiceProxy.getUserManagementService(getServlet().getServletContext()); - + HttpServletResponse response) throws IOException { + IUserManagementService userManagementService = MonitoringServiceProxy + .getUserManagementService(getServlet().getServletContext()); + Integer organisationId = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID); String newGroupingName = request.getParameter("name"); // Checks if a course grouping name is unique inside of this group and thus new group can have it - HashMap properties = new HashMap(); + HashMap properties = new HashMap<>(); properties.put("organisationId", organisationId); properties.put("name", newGroupingName); List orgGroupings = userManagementService.findByProperties(OrganisationGrouping.class, properties); boolean isGroupingNameUnique = orgGroupings.isEmpty(); - - JSONObject responseJSON = new JSONObject(); + + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); responseJSON.put("isGroupingNameUnique", isGroupingNameUnique); response.setContentType("application/json;charset=utf-8"); response.getWriter().write(responseJSON.toString()); @@ -397,7 +400,7 @@ * Checks if a group can be removed and performs it. */ public ActionForward removeGroup(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { response.setContentType("application/json;charset=utf-8"); Long activityID = WebUtil.readLongParam(request, AttributeNames.PARAM_ACTIVITY_ID); Long groupID = WebUtil.readLongParam(request, AttributeNames.PARAM_GROUP_ID); @@ -421,12 +424,12 @@ result = false; } } - JSONObject responseJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); responseJSON.put("result", result); response.getWriter().write(responseJSON.toString()); return null; } - + private ISecurityService getSecurityService() { if (securityService == null) { WebApplicationContext ctx = WebApplicationContextUtils Index: lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/GroupingUploadAJAXAction.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/GroupingUploadAJAXAction.java (.../GroupingUploadAJAXAction.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/GroupingUploadAJAXAction.java (.../GroupingUploadAJAXAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -51,14 +51,12 @@ import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellType; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; 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 { IMonitoringFullService 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(CellType.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 -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/MonitoringAction.java (.../MonitoringAction.java) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_monitoring/src/java/org/lamsfoundation/lams/monitoring/web/MonitoringAction.java (.../MonitoringAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -52,9 +52,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.IAuthoringService; import org.lamsfoundation.lams.learning.service.ILearnerService; import org.lamsfoundation.lams.learningdesign.Activity; @@ -92,6 +89,7 @@ import org.lamsfoundation.lams.usermanagement.service.IUserManagementService; import org.lamsfoundation.lams.util.CommonConstants; 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; @@ -102,8 +100,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 @@ -232,14 +231,14 @@ response.getWriter().write("true"); return null; } - + /** * Renames lesson. Invoked by Ajax call from general LAMS monitoring. */ public ActionForward renameLesson(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException, JSONException { + HttpServletResponse response) throws IOException, ServletException { long lessonId = WebUtil.readLongParam(request, "pk"); - + HttpSession ss = SessionManager.getSession(); UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); if (!getSecurityService().isLessonMonitor(lessonId, user.getUserID(), "rename lesson", false)) { @@ -256,7 +255,7 @@ lesson.setLessonName(newLessonName); getUserManagementService().save(lesson); - JSONObject jsonObject = new JSONObject(); + ObjectNode jsonObject = JsonNodeFactory.instance.objectNode(); jsonObject.put("successful", true); response.setContentType("application/json;charset=utf-8"); response.getWriter().print(jsonObject); @@ -312,13 +311,13 @@ boolean schedulingEnable = WebUtil.readBooleanParam(request, "schedulingEnable", false); Date schedulingDatetime = null; Date schedulingEndDatetime = null; - if ( schedulingEnable ) { + if (schedulingEnable) { String dateString = request.getParameter("schedulingDatetime"); - if ( dateString != null && dateString.length() > 0 ) { + if (dateString != null && dateString.length() > 0) { schedulingDatetime = MonitoringAction.LESSON_SCHEDULING_DATETIME_FORMAT.parse(dateString); } dateString = request.getParameter("schedulingEndDatetime"); - if ( dateString != null && dateString.length() > 0 ) { + if (dateString != null && dateString.length() > 0) { schedulingEndDatetime = MonitoringAction.LESSON_SCHEDULING_DATETIME_FORMAT.parse(dateString); } } @@ -355,7 +354,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; @@ -411,12 +410,13 @@ // monitor has given an end date/time for the lesson if (schedulingEndDatetime != null) { - getMonitoringService().finishLessonOnSchedule(lesson.getLessonId(), schedulingEndDatetime, userId); - // if lesson should finish in few days, set it here + getMonitoringService().finishLessonOnSchedule(lesson.getLessonId(), schedulingEndDatetime, + userId); + // if lesson should finish in few days, set it here } else if (timeLimitLesson != null) { getMonitoringService().finishLessonOnSchedule(lesson.getLessonId(), timeLimitLesson, userId); } - + } catch (SecurityException e) { try { response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a monitor in the lesson"); @@ -510,11 +510,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"); } @@ -557,7 +558,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); @@ -569,7 +570,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 @@ -603,7 +604,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; @@ -622,7 +623,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(); @@ -665,7 +666,7 @@ // audit log force completion attempt String messageKey = (activityId == null) ? "audit.force.complete.end.lesson" : "audit.force.complete"; - + Object[] args = new Object[] { learnerIdNameBuf.toString(), activityDescription, lessonId }; String auditMessage = getMonitoringService().getMessageService().getMessage(messageKey, args); getLogEventService().logEvent(LogEvent.TYPE_FORCE_COMPLETE, requesterId, null, lessonId, activityId, @@ -680,7 +681,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"); @@ -696,15 +697,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()); @@ -715,7 +716,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"); @@ -733,7 +734,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, @@ -746,18 +747,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()); @@ -768,8 +769,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); @@ -790,7 +791,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); @@ -803,21 +804,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()); @@ -828,7 +829,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"); @@ -873,7 +874,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")); @@ -998,45 +999,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"); } @@ -1048,7 +1051,7 @@ || CommonConstants.TOOL_SIGNATURE_MCQ .equals(((ToolActivity) activity).getTool().getToolSignature()))) { return verifyNextActivityFitsTbl(nextActivity, "Leaderselection"); - + } else { return verifyNextActivityFitsTbl(nextActivity, "MCQ or Assessment"); } @@ -1058,20 +1061,20 @@ if (activity.isToolActivity() && CommonConstants.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() && CommonConstants.TOOL_SIGNATURE_SCRATCHIE .equals(((ToolActivity) activity).getTool().getToolSignature())) { return true; - + } else if (nextActivity == null) { return false; - + } else { return verifyNextActivityFitsTbl(nextActivity, "Scratchie"); } @@ -1085,7 +1088,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"); @@ -1104,9 +1107,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 @@ -1120,7 +1123,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); @@ -1130,7 +1133,7 @@ return null; } - JSONObject responseJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); Lesson lesson = getLessonService().getLesson(lessonId); LearningDesign learningDesign = lesson.getLearningDesign(); @@ -1148,25 +1151,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"); @@ -1175,7 +1178,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); @@ -1184,21 +1187,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()); @@ -1210,7 +1213,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)) { @@ -1223,7 +1226,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()) { @@ -1234,11 +1237,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 @@ -1249,8 +1251,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 @@ -1266,10 +1268,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()); @@ -1332,23 +1334,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, @@ -1367,25 +1369,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"); @@ -1420,13 +1422,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"); @@ -1656,9 +1658,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, @@ -1708,7 +1710,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(); @@ -1729,7 +1731,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 @@ -1740,7 +1742,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()) { @@ -1776,7 +1778,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/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_assessment/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_assessment/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -9,19 +9,21 @@ - - + + - - + + - + + + Index: lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java =================================================================== diff -u -re2ab99460f405e52267d81c35ddb19b37edff7f3 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java (.../AssessmentServiceImpl.java) (revision e2ab99460f405e52267d81c35ddb19b37edff7f3) +++ lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java (.../AssessmentServiceImpl.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -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.contentrepository.client.IToolContentHandler; import org.lamsfoundation.lams.events.IEventNotificationService; @@ -114,6 +112,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 */ @@ -808,9 +811,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()) { @@ -877,11 +880,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) { @@ -998,7 +1001,7 @@ @Override public List getReflectList(Long contentId) { - List reflectList = new LinkedList(); + List reflectList = new LinkedList<>(); List sessionList = assessmentSessionDao.getByContentId(contentId); for (AssessmentSession session : sessionList) { @@ -1049,7 +1052,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) { @@ -1112,7 +1115,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()) { @@ -1160,7 +1163,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()); @@ -1173,12 +1176,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())) { @@ -1213,27 +1216,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()) { @@ -1253,14 +1256,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; @@ -1309,12 +1312,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) { @@ -1326,7 +1329,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()) { @@ -1352,7 +1355,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, @@ -1441,7 +1444,7 @@ // ------------------------------------------------------------------ // -------------- Second tab: Question Summary ---------------------- - ArrayList questionSummaryTab = new ArrayList(); + ArrayList questionSummaryTab = new ArrayList<>(); // Create the question summary ExcelCell[] summaryTitle = new ExcelCell[1]; @@ -1497,15 +1500,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) { @@ -1668,7 +1671,7 @@ // ------------------------------------------------------------------ // -------------- Third tab: User Summary --------------------------- - ArrayList userSummaryTab = new ArrayList(); + ArrayList userSummaryTab = new ArrayList<>(); // Create the question summary ExcelCell[] userSummaryTitle = new ExcelCell[1]; @@ -1690,7 +1693,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; @@ -1746,7 +1749,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); } @@ -2010,11 +2013,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); } @@ -2058,7 +2061,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())) { @@ -2104,7 +2107,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()) @@ -2115,7 +2118,7 @@ } // create list of added references - List addedReferences = new ArrayList(); + List addedReferences = new ArrayList<>(); for (QuestionReference newReference : newReferences) { boolean isNewReferenceMetInOldReferences = false; @@ -2224,7 +2227,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() @@ -2372,8 +2375,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; @@ -2875,7 +2878,7 @@ public void setCoreNotebookService(ICoreNotebookService coreNotebookService) { this.coreNotebookService = coreNotebookService; } - + public void setLearnerService(ILearnerService learnerService) { this.learnerService = learnerService; } @@ -2939,99 +2942,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) @@ -3040,22 +3050,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); } @@ -3067,23 +3076,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); } @@ -3105,10 +3114,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); } @@ -3125,7 +3134,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) { @@ -3134,7 +3143,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/web/action/AuthoringAction.java =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/AuthoringAction.java (.../AuthoringAction.java) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/AuthoringAction.java (.../AuthoringAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -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 -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/LearningAction.java (.../LearningAction.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/LearningAction.java (.../LearningAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -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.learningdesign.dto.ActivityPositionDTO; import org.lamsfoundation.lams.notebook.model.NotebookEntry; import org.lamsfoundation.lams.tool.ToolAccessMode; @@ -90,6 +88,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 */ @@ -100,7 +101,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")) { @@ -163,7 +164,7 @@ InvocationTargetException, NoSuchMethodException { // initialize Session Map - SessionMap sessionMap = new SessionMap(); + SessionMap sessionMap = new SessionMap<>(); request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap); // save toolContentID into HTTPSession @@ -206,7 +207,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()); @@ -241,10 +243,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) { @@ -337,7 +339,7 @@ } //sort questions - LinkedList questionDtos = new LinkedList(); + LinkedList questionDtos = new LinkedList<>(); for (QuestionReference questionReference : questionReferences) { AssessmentQuestion question = questionToReferenceMap.get(questionReference.getUid()); @@ -349,20 +351,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) { @@ -372,8 +373,8 @@ return AlphanumComparator.compareAlphnumerically(optionString1, optionString2); } }); - questionDto.setMatchingPairOptions(new LinkedHashSet(optionsSortedByOptionString)); - } + questionDto.setMatchingPairOptions(new LinkedHashSet<>(optionsSortedByOptionString)); + } } //paging @@ -388,7 +389,7 @@ questionsForOnePage.add(questionDto); count++; if ((questionsForOnePage.size() == maxQuestionsPerPage) && (count != questionDtos.size())) { - questionsForOnePage = new LinkedHashSet(); + questionsForOnePage = new LinkedHashSet<>(); pagedQuestionDtos.add(questionsForOnePage); } } @@ -421,7 +422,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); @@ -433,10 +434,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; } @@ -527,7 +528,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); @@ -536,10 +537,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; } @@ -638,7 +639,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) { @@ -763,7 +763,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); @@ -774,7 +774,7 @@ } // put back list - optionDtoList = new LinkedHashSet(rList); + optionDtoList = new LinkedHashSet<>(rList); questionDto.setOptionDtos(optionDtoList); } @@ -1267,7 +1267,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 -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/MonitoringAction.java (.../MonitoringAction.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/web/action/MonitoringAction.java (.../MonitoringAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -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.tool.assessment.AssessmentConstants; import org.lamsfoundation.lams.tool.assessment.dto.AssessmentResultDTO; import org.lamsfoundation.lams.tool.assessment.dto.AssessmentUserDTO; @@ -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,55 @@ 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.add(questionResultUid); + userData.add(questionResult.getMaxMark()); + userData.add(fullName); //LDEV_NTU-11 Swapping Mark and Response columns in Assessment Monitor - userData.put(questionResult.getMark()); + userData.add(questionResult.getMark()); // show confidence levels if this feature is turned ON if (assessment.isEnableConfidenceLevels()) { - userData.put(questionResult.getConfidenceLevel()); + userData.add(questionResult.getConfidenceLevel()); } - userData.put(AssessmentEscapeUtils.printResponsesForJqgrid(questionResult)); + + userData.add(AssessmentEscapeUtils.printResponsesForJqgrid(questionResult)); 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 +553,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 +575,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 +678,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 +701,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_bbb/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_bbb/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_bbb/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -5,7 +5,7 @@ - + @@ -15,13 +15,13 @@ - - + + - + Index: lams_tool_chat/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_chat/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_chat/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -4,7 +4,7 @@ - + @@ -15,13 +15,15 @@ - + - - + + + + Index: lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/service/ChatService.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/service/ChatService.java (.../ChatService.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_tool_chat/src/java/org/lamsfoundation/lams/tool/chat/service/ChatService.java (.../ChatService.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -36,8 +36,6 @@ import java.util.regex.Pattern; import org.apache.log4j.Logger; -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.learningdesign.service.ExportToolContentException; @@ -74,6 +72,8 @@ import org.lamsfoundation.lams.usermanagement.dto.UserDTO; import org.lamsfoundation.lams.util.JsonUtil; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * An implementation of the IChatService interface. * @@ -200,9 +200,9 @@ @Override public List getToolOutputs(String name, Long toolContentId) { - return new ArrayList(); + return new ArrayList<>(); } - + @Override public List getConfidenceLevels(Long toolSessionId) { return null; @@ -667,14 +667,14 @@ public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } - + @Override public void auditLogStartEditingActivityInMonitor(long toolContentID) { - toolService.auditLogStartEditingActivityInMonitor(toolContentID); + toolService.auditLogStartEditingActivityInMonitor(toolContentID); } /* Private methods */ - private Map messageFilters = new ConcurrentHashMap(); + private Map messageFilters = new ConcurrentHashMap<>(); public IChatDAO getChatDAO() { return chatDAO; @@ -817,7 +817,7 @@ public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getChatOutputFactory().getSupportedDefinitionClasses(definitionType); } - + @Override public ToolCompletionStatus getCompletionStatus(Long learnerId, Long toolSessionId) { ChatUser learner = getUserByUserIdAndSessionId(learnerId, toolSessionId); @@ -828,20 +828,23 @@ Date startDate = null; Date endDate = learner.getLastPresence(); List messages = getMessagesForUser(learner); - for ( ChatMessage message : messages ) { + for (ChatMessage message : messages) { Date sendDate = message.getSendDate(); - if ( sendDate != null ) { - if ( startDate == null || sendDate.before(startDate) ) + if (sendDate != null) { + if (startDate == null || sendDate.before(startDate)) { startDate = sendDate; - if ( endDate == null || sendDate.after(endDate) ) + } + if (endDate == null || sendDate.after(endDate)) { endDate = sendDate; + } } } - - if (learner.isFinishedActivity()) + + if (learner.isFinishedActivity()) { return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_COMPLETED, startDate, endDate); - else + } else { return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_ATTEMPTED, startDate, null); + } } // ========================================================================================= @@ -852,25 +855,24 @@ * fields reflectInstructions, lockWhenFinished, filterKeywords */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) { Chat content = new Chat(); Date updateDate = new Date(); content.setCreateDate(updateDate); content.setUpdateDate(updateDate); content.setToolContentId(toolContentID); - content.setTitle(toolContentJSON.getString(RestTags.TITLE)); - content.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); + content.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE)); + content.setInstructions(JsonUtil.optString(toolContentJSON, RestTags.INSTRUCTIONS)); content.setCreateBy(userID.longValue()); content.setContentInUse(false); content.setDefineLater(false); - content.setReflectInstructions((String) JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, null)); - content.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - content.setLockOnFinished(JsonUtil.opt(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); + content.setReflectInstructions(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS)); + content.setReflectOnActivity(JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); + content.setLockOnFinished(JsonUtil.optBoolean(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); - String filterKeywords = JsonUtil.opt(toolContentJSON, "filterKeywords", null); + String filterKeywords = JsonUtil.optString(toolContentJSON, "filterKeywords"); content.setFilteringEnabled((filterKeywords != null) && (filterKeywords.length() > 0)); content.setFilterKeywords(filterKeywords); // submissionDeadline is set in monitoring Index: lams_tool_daco/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_daco/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_daco/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -3,7 +3,7 @@ - + @@ -15,12 +15,14 @@ - - + + - + + + Index: lams_tool_daco/src/java/org/lamsfoundation/lams/tool/daco/web/action/MonitoringAction.java =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_daco/src/java/org/lamsfoundation/lams/tool/daco/web/action/MonitoringAction.java (.../MonitoringAction.java) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_daco/src/java/org/lamsfoundation/lams/tool/daco/web/action/MonitoringAction.java (.../MonitoringAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -21,7 +21,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.tool.daco.web.action; import java.io.IOException; @@ -45,9 +44,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.notebook.model.NotebookEntry; import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; import org.lamsfoundation.lams.tool.daco.DacoConstants; @@ -73,12 +69,16 @@ 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); @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException, ParseException, JSONException { + HttpServletResponse response) throws IOException, ServletException, ParseException { String param = mapping.getParameter(); if (param.equals("summary")) { @@ -200,7 +200,7 @@ } protected ActionForward getUsers(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse res) throws IOException, ServletException, JSONException { + HttpServletResponse res) throws IOException, ServletException { IDacoService service = getDacoService(); String sessionMapID = WebUtil.readStrParam(request, DacoConstants.ATTR_SESSION_MAP_ID, true); @@ -238,22 +238,22 @@ List users = service.getUsersForTablesorter(sessionId, page, size, sorting, searchString, daco.isReflectOnActivity()); - JSONArray rows = new JSONArray(); + ArrayNode rows = JsonNodeFactory.instance.arrayNode(); - JSONObject responsedata = new JSONObject(); + 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(); DacoUser user = (DacoUser) userAndReflection[0]; responseRow.put(DacoConstants.USER_ID, user.getUserId()); responseRow.put(DacoConstants.USER_FULL_NAME, HtmlUtils.htmlEscape(user.getFullName())); if (userAndReflection.length > 1 && userAndReflection[1] != null) { - responseRow.put(DacoConstants.RECORD_COUNT, userAndReflection[1]); + responseRow.put(DacoConstants.RECORD_COUNT, (Integer) userAndReflection[1]); } else { responseRow.put(DacoConstants.RECORD_COUNT, 0); } @@ -263,11 +263,11 @@ HtmlUtils.htmlEscape((String) userAndReflection[2])); } if (userAndReflection.length > 3 && userAndReflection[3] != null) { - responseRow.put(DacoConstants.PORTRAIT_ID, userAndReflection[3]); + responseRow.put(DacoConstants.PORTRAIT_ID, (String) userAndReflection[3]); } - rows.put(responseRow); + rows.add(responseRow); } - responsedata.put("rows", rows); + responsedata.set("rows", rows); res.setContentType("application/json;charset=utf-8"); res.getWriter().print(new String(responsedata.toString())); return null; @@ -320,7 +320,7 @@ String dateHeader = service.getLocalisedMessage(DacoConstants.KEY_LABEL_EXPORT_FILE_DATE, null); Set questions = daco.getDacoQuestions(); - HashMap questionUidToSpreadsheetColumnIndex = new HashMap(); + HashMap questionUidToSpreadsheetColumnIndex = new HashMap<>(); // First two columns are "user" and date when was the answer added int columnIndex = 2; String[] columnNames = new String[questions.size() + 2]; @@ -339,7 +339,7 @@ String latitudeHeader = service.getLocalisedMessage(DacoConstants.KEY_LABEL_LEARNING_LONGLAT_LATITUDE, null); String latitudeUnit = service.getLocalisedMessage(DacoConstants.KEY_LABEL_LEARNING_LONGLAT_LATITUDE_UNIT, null); - List rows = new LinkedList(); + List rows = new LinkedList<>(); // We get all sessions with all users with all their records from the given Daco content List monitoringSummary = service.getSummaryForExport(daco.getContentId(), null); // Get current user's locale to format numbers properly @@ -397,7 +397,7 @@ if (!StringUtils.isBlank(answerString)) { DacoQuestion question = answer.getQuestion(); DacoQuestion currentQuestion = question; - List answerOptions = new LinkedList( + List answerOptions = new LinkedList<>( question.getAnswerOptions()); StringBuilder cellStringBuilder = new StringBuilder(); // instead of number, we create a comma-separated string of chosen options @@ -451,7 +451,7 @@ case DacoConstants.QUESTION_TYPE_RADIO: case DacoConstants.QUESTION_TYPE_DROPDOWN: if (!StringUtils.isBlank(answerString)) { - List answerOptions = new LinkedList( + List answerOptions = new LinkedList<>( answer.getQuestion().getAnswerOptions()); try { int chosenAnswer = Integer.parseInt(answerString) - 1; Index: lams_tool_dimdim/.classpath =================================================================== diff -u -rf4502360cd44d86d57b095aea5aef7ce663c8b61 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_dimdim/.classpath (.../.classpath) (revision f4502360cd44d86d57b095aea5aef7ce663c8b61) +++ lams_tool_dimdim/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -8,7 +8,7 @@ - + Index: lams_tool_doku/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_doku/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_doku/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -3,7 +3,7 @@ - + @@ -15,14 +15,16 @@ - - + + - - + + + + Index: lams_tool_doku/src/java/org/lamsfoundation/lams/tool/dokumaran/service/DokumaranService.java =================================================================== diff -u -re2ab99460f405e52267d81c35ddb19b37edff7f3 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_doku/src/java/org/lamsfoundation/lams/tool/dokumaran/service/DokumaranService.java (.../DokumaranService.java) (revision e2ab99460f405e52267d81c35ddb19b37edff7f3) +++ lams_tool_doku/src/java/org/lamsfoundation/lams/tool/dokumaran/service/DokumaranService.java (.../DokumaranService.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -40,8 +40,6 @@ import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; -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.learningdesign.service.ExportToolContentException; @@ -80,6 +78,8 @@ import org.lamsfoundation.lams.util.JsonUtil; import org.lamsfoundation.lams.util.MessageService; +import com.fasterxml.jackson.databind.node.ObjectNode; + import net.gjerull.etherpad.client.EPLiteClient; import net.gjerull.etherpad.client.EPLiteException; @@ -272,14 +272,14 @@ } @Override - public void launchTimeLimit(Long toolContentId) throws JSONException, IOException { + public void launchTimeLimit(Long toolContentId) throws IOException { Dokumaran dokumaran = getDokumaranByContentId(toolContentId); dokumaran.setTimeLimitLaunchedDate(new Date()); dokumaranDao.saveObject(dokumaran); } @Override - public void addOneMinute(Long toolContentId) throws JSONException, IOException { + public void addOneMinute(Long toolContentId) throws IOException { Dokumaran dokumaran = getDokumaranByContentId(toolContentId); int timeLimit = dokumaran.getTimeLimit(); @@ -1032,7 +1032,7 @@ public List getToolOutputs(String name, Long toolContentId) { return new ArrayList<>(); } - + @Override public List getConfidenceLevels(Long toolSessionId) { return null; @@ -1107,41 +1107,42 @@ /** * Used by the Rest calls to create content. Mandatory fields in toolContentJSON: title, instructions, dokumaran, - * user fields firstName, lastName and loginName Dokumaran must contain a JSONArray of JSONObject objects, which + * user fields firstName, lastName and loginName Dokumaran must contain a ArrayNode of ObjectNode objects, which * have the following mandatory fields: title, description, type. If there are instructions for a dokumaran, the - * instructions are a JSONArray of Strings. There should be at least one dokumaran object in the dokumaran array. + * instructions are a ArrayNode of Strings. There should be at least one dokumaran object in the dokumaran array. */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) { Date updateDate = new Date(); Dokumaran dokumaran = new Dokumaran(); dokumaran.setContentId(toolContentID); - dokumaran.setTitle(toolContentJSON.getString(RestTags.TITLE)); - dokumaran.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); + dokumaran.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE)); + dokumaran.setInstructions(JsonUtil.optString(toolContentJSON, RestTags.INSTRUCTIONS)); dokumaran.setCreated(updateDate); - dokumaran.setTimeLimit(JsonUtil.opt(toolContentJSON, "timeLimit", 0)); - dokumaran.setShowChat(JsonUtil.opt(toolContentJSON, "showChat", Boolean.FALSE)); - dokumaran.setShowLineNumbers(JsonUtil.opt(toolContentJSON, "showLineNumbers", Boolean.FALSE)); - dokumaran.setSharedPadId(JsonUtil.opt(toolContentJSON, "sharedPadId", (String) null)); - dokumaran.setLockWhenFinished(JsonUtil.opt(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); - dokumaran.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - dokumaran.setReflectInstructions(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, (String) null)); - dokumaran.setUseSelectLeaderToolOuput(JsonUtil.opt(toolContentJSON, "useSelectLeaderToolOuput", Boolean.FALSE)); - dokumaran.setAllowMultipleLeaders(JsonUtil.opt(toolContentJSON, "allowMultipleLeaders", Boolean.FALSE)); + dokumaran.setTimeLimit(JsonUtil.optInt(toolContentJSON, "timeLimit", 0)); + dokumaran.setShowChat(JsonUtil.optBoolean(toolContentJSON, "showChat", Boolean.FALSE)); + dokumaran.setShowLineNumbers(JsonUtil.optBoolean(toolContentJSON, "showLineNumbers", Boolean.FALSE)); + dokumaran.setSharedPadId(JsonUtil.optString(toolContentJSON, "sharedPadId")); + dokumaran.setLockWhenFinished(JsonUtil.optBoolean(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); + dokumaran.setReflectOnActivity( + JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); + dokumaran.setReflectInstructions(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS)); + dokumaran.setUseSelectLeaderToolOuput( + JsonUtil.optBoolean(toolContentJSON, "useSelectLeaderToolOuput", Boolean.FALSE)); + dokumaran.setAllowMultipleLeaders(JsonUtil.optBoolean(toolContentJSON, "allowMultipleLeaders", Boolean.FALSE)); dokumaran.setContentInUse(false); dokumaran.setDefineLater(false); DokumaranUser dokumaranUser = getUserByIDAndContent(userID.longValue(), toolContentID); if (dokumaranUser == null) { dokumaranUser = new DokumaranUser(); - dokumaranUser.setFirstName(toolContentJSON.getString("firstName")); - dokumaranUser.setLastName(toolContentJSON.getString("lastName")); - dokumaranUser.setLoginName(toolContentJSON.getString("loginName")); + dokumaranUser.setFirstName(JsonUtil.optString(toolContentJSON, "firstName")); + dokumaranUser.setLastName(JsonUtil.optString(toolContentJSON, "lastName")); + dokumaranUser.setLoginName(JsonUtil.optString(toolContentJSON, "loginName")); // dokumaranUser.setDokumaran(content); } Index: lams_tool_doku/src/java/org/lamsfoundation/lams/tool/dokumaran/web/action/LearningAction.java =================================================================== diff -u -rf4502360cd44d86d57b095aea5aef7ce663c8b61 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_doku/src/java/org/lamsfoundation/lams/tool/dokumaran/web/action/LearningAction.java (.../LearningAction.java) (revision f4502360cd44d86d57b095aea5aef7ce663c8b61) +++ lams_tool_doku/src/java/org/lamsfoundation/lams/tool/dokumaran/web/action/LearningAction.java (.../LearningAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -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.learningdesign.dto.ActivityPositionDTO; import org.lamsfoundation.lams.notebook.model.NotebookEntry; import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; @@ -64,6 +62,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 Steve.Ni */ @@ -75,7 +76,8 @@ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException, JSONException, DokumaranConfigurationException, URISyntaxException, DokumaranApplicationException { + HttpServletResponse response) throws IOException, ServletException, DokumaranConfigurationException, + URISyntaxException, DokumaranApplicationException { String param = mapping.getParameter(); // -----------------------Dokumaran Learner function --------------------------- @@ -105,15 +107,17 @@ * method run successfully. * * This method will avoid read database again and lost un-saved resouce item lost when user "refresh page", - * @throws DokumaranConfigurationException - * @throws URISyntaxException * + * @throws DokumaranConfigurationException + * @throws URISyntaxException + * */ private ActionForward start(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws DokumaranConfigurationException, DokumaranApplicationException, URISyntaxException { + HttpServletResponse response) + throws DokumaranConfigurationException, DokumaranApplicationException, URISyntaxException { // initial Session Map - SessionMap sessionMap = new SessionMap(); + SessionMap sessionMap = new SessionMap<>(); request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap); request.setAttribute(DokumaranConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID()); @@ -146,14 +150,15 @@ // support for leader select feature List leaders = dokumaran.isUseSelectLeaderToolOuput() - ? service.checkLeaderSelectToolForSessionLeader(user, new Long(toolSessionId).longValue(), isFirstTimeAccess) - : new ArrayList(); + ? service.checkLeaderSelectToolForSessionLeader(user, new Long(toolSessionId).longValue(), + isFirstTimeAccess) + : new ArrayList<>(); // forwards to the leaderSelection page if (dokumaran.isUseSelectLeaderToolOuput() && leaders.isEmpty() && !mode.isTeacher()) { - + // get group users and store it to request as DTO objects List groupUsers = service.getUsersBySession(toolSessionId); - List groupUserDtos = new ArrayList(); + List groupUserDtos = new ArrayList<>(); for (DokumaranUser groupUser : groupUsers) { User groupUserDto = new User(); groupUserDto.setFirstName(groupUser.getFirstName()); @@ -168,7 +173,7 @@ if (dokumaran.getTimeLimit() > 0 && dokumaran.getTimeLimitLaunchedDate() == null) { return mapping.findForward("waitForTimeLimitLaunch"); } - + boolean isUserLeader = (user != null) && service.isUserLeader(leaders, user.getUserId()); // check whether finish lock is on/off @@ -183,7 +188,8 @@ sessionMap.put(DokumaranConstants.ATTR_LOCK_ON_FINISH, dokumaran.getLockWhenFinished()); sessionMap.put(DokumaranConstants.ATTR_USER_FINISHED, (user != null) && user.isSessionFinished()); sessionMap.put(DokumaranConstants.ATTR_HAS_EDIT_RIGHT, hasEditRight); - sessionMap.put(DokumaranConstants.ATTR_IS_LEADER_RESPONSE_FINALIZED, service.isLeaderResponseFinalized(leaders)); + sessionMap.put(DokumaranConstants.ATTR_IS_LEADER_RESPONSE_FINALIZED, + service.isLeaderResponseFinalized(leaders)); sessionMap.put(AttributeNames.PARAM_TOOL_SESSION_ID, toolSessionId); sessionMap.put(AttributeNames.ATTR_MODE, mode); @@ -215,23 +221,25 @@ sessionMap.put(AttributeNames.ATTR_ACTIVITY_POSITION, activityPosition); sessionMap.put(DokumaranConstants.ATTR_DOKUMARAN, dokumaran); - + // get the API key from the config table and add it to the session - DokumaranConfigItem etherpadServerUrlConfig = dokumaranService.getConfigItem(DokumaranConfigItem.KEY_ETHERPAD_URL); + DokumaranConfigItem etherpadServerUrlConfig = dokumaranService + .getConfigItem(DokumaranConfigItem.KEY_ETHERPAD_URL); DokumaranConfigItem apiKeyConfig = dokumaranService.getConfigItem(DokumaranConfigItem.KEY_API_KEY); - if (apiKeyConfig == null || apiKeyConfig.getConfigValue() == null || etherpadServerUrlConfig == null || etherpadServerUrlConfig.getConfigValue() == null) { + if (apiKeyConfig == null || apiKeyConfig.getConfigValue() == null || etherpadServerUrlConfig == null + || etherpadServerUrlConfig.getConfigValue() == null) { return mapping.findForward("notconfigured"); } String etherpadServerUrl = etherpadServerUrlConfig.getConfigValue(); request.setAttribute(DokumaranConstants.KEY_ETHERPAD_SERVER_URL, etherpadServerUrl); - + //time limit boolean isTimeLimitEnabled = hasEditRight && !finishedLock && dokumaran.getTimeLimit() != 0; long secondsLeft = isTimeLimitEnabled ? service.getSecondsLeft(dokumaran) : 0; request.setAttribute(DokumaranConstants.ATTR_SECONDS_LEFT, secondsLeft); - + boolean isTimeLimitExceeded = service.checkTimeLimitExceeded(dokumaran); - + String padId = session.getPadId(); //in case of non-leader or finished lock or isTimeLimitExceeded - show Etherpad in readonly mode if (dokumaran.isUseSelectLeaderToolOuput() && !isUserLeader || finishedLock || isTimeLimitExceeded) { @@ -242,7 +250,7 @@ } } request.setAttribute(DokumaranConstants.ATTR_PAD_ID, padId); - + //add new sessionID cookie in order to access pad if (user != null) { Cookie etherpadSessionCookie = service.createEtherpadCookieForLearner(user, session); @@ -251,22 +259,22 @@ return mapping.findForward(DokumaranConstants.SUCCESS); } - + /** * Checks Leader Progress */ private ActionForward checkLeaderProgress(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { IDokumaranService service = getDokumaranService(); Long toolSessionId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID); boolean isLeaderResponseFinalized = service.isLeaderResponseFinalized(toolSessionId); - JSONObject JSONObject = new JSONObject(); - JSONObject.put(DokumaranConstants.ATTR_IS_LEADER_RESPONSE_FINALIZED, isLeaderResponseFinalized); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); + responseJSON.put(DokumaranConstants.ATTR_IS_LEADER_RESPONSE_FINALIZED, isLeaderResponseFinalized); response.setContentType("application/x-json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(responseJSON); return null; } @@ -399,8 +407,8 @@ private DokumaranUser getSpecifiedUser(IDokumaranService service, Long sessionId, Integer userId) { DokumaranUser dokumaranUser = service.getUserByIDAndSession(new Long(userId.intValue()), sessionId); if (dokumaranUser == null) { - LearningAction.log - .error("Unable to find specified user for dokumaran activity. Screens are likely to fail. SessionId=" + LearningAction.log.error( + "Unable to find specified user for dokumaran activity. Screens are likely to fail. SessionId=" + sessionId + " UserId=" + userId); } return dokumaranUser; Index: lams_tool_eadventure/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_eadventure/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_eadventure/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -5,24 +5,23 @@ - + - + - + - - + Index: lams_tool_forum/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_forum/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_forum/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -9,18 +9,20 @@ - + - - + + - + + + Index: lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/service/ForumService.java =================================================================== diff -u -re2ab99460f405e52267d81c35ddb19b37edff7f3 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/service/ForumService.java (.../ForumService.java) (revision e2ab99460f405e52267d81c35ddb19b37edff7f3) +++ lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/service/ForumService.java (.../ForumService.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -42,9 +42,6 @@ import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.struts.upload.FormFile; -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.NodeKey; import org.lamsfoundation.lams.contentrepository.client.IToolContentHandler; @@ -108,6 +105,9 @@ import org.lamsfoundation.lams.util.JsonUtil; import org.lamsfoundation.lams.util.MessageService; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * * @author Steve.Ni @@ -1472,50 +1472,49 @@ /** * Used by the Rest calls to create content. Mandatory fields in toolContentJSON: title, instructions, topics. - * Topics must contain a JSONArray of JSONObject objects, which have the following mandatory fields: subject, body + * Topics must contain a ArrayNode of ObjectNode objects, which have the following mandatory fields: subject, body * There will usually be at least one topic object in the Topics array but the array may be of zero length. */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) { Forum forum = new Forum(); Date updateDate = new Date(); forum.setCreated(updateDate); forum.setUpdated(updateDate); forum.setContentId(toolContentID); - forum.setTitle(toolContentJSON.getString(RestTags.TITLE)); - forum.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); + forum.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE)); + forum.setInstructions(JsonUtil.optString(toolContentJSON, RestTags.INSTRUCTIONS)); - forum.setAllowAnonym(JsonUtil.opt(toolContentJSON, "allowAnonym", Boolean.FALSE)); - forum.setAllowEdit(JsonUtil.opt(toolContentJSON, "allowEdit", Boolean.TRUE)); // defaults to true in the default - // entry in the db - forum.setAllowNewTopic(JsonUtil.opt(toolContentJSON, "allowNewTopic", Boolean.TRUE)); // defaults to true in the - // default entry in the db - forum.setAllowRateMessages(JsonUtil.opt(toolContentJSON, "allowRateMessages", Boolean.FALSE)); - forum.setAllowRichEditor(JsonUtil.opt(toolContentJSON, RestTags.ALLOW_RICH_TEXT_EDITOR, Boolean.FALSE)); - forum.setAllowUpload(JsonUtil.opt(toolContentJSON, "allowUpload", Boolean.FALSE)); + forum.setAllowAnonym(JsonUtil.optBoolean(toolContentJSON, "allowAnonym", Boolean.FALSE)); + forum.setAllowEdit(JsonUtil.optBoolean(toolContentJSON, "allowEdit", Boolean.TRUE)); // defaults to true in the default + // entry in the db + forum.setAllowNewTopic(JsonUtil.optBoolean(toolContentJSON, "allowNewTopic", Boolean.TRUE)); // defaults to true in the + // default entry in the db + forum.setAllowRateMessages(JsonUtil.optBoolean(toolContentJSON, "allowRateMessages", Boolean.FALSE)); + forum.setAllowRichEditor(JsonUtil.optBoolean(toolContentJSON, RestTags.ALLOW_RICH_TEXT_EDITOR, Boolean.FALSE)); + forum.setAllowUpload(JsonUtil.optBoolean(toolContentJSON, "allowUpload", Boolean.FALSE)); forum.setContentInUse(false); forum.setDefineLater(false); - forum.setLimitedMaxCharacters(JsonUtil.opt(toolContentJSON, "limitedMaxCharacters", Boolean.TRUE)); - forum.setLimitedMinCharacters(JsonUtil.opt(toolContentJSON, "limitedMinCharacters", Boolean.FALSE)); - forum.setLockWhenFinished(JsonUtil.opt(toolContentJSON, "lockWhenFinished", Boolean.FALSE)); - forum.setMaxCharacters(JsonUtil.opt(toolContentJSON, "maxCharacters", 5000)); // defaults to 5000 chars in the - // default entry in the db. - forum.setMaximumRate(JsonUtil.opt(toolContentJSON, "maximumRate", 0)); - forum.setMaximumReply(JsonUtil.opt(toolContentJSON, "maximumReply", 0)); - forum.setMinCharacters(JsonUtil.opt(toolContentJSON, "minCharacters", 0)); - forum.setMinimumRate(JsonUtil.opt(toolContentJSON, "minimumRate", 0)); - forum.setMinimumReply(JsonUtil.opt(toolContentJSON, "minimumReply", 0)); + forum.setLimitedMaxCharacters(JsonUtil.optBoolean(toolContentJSON, "limitedMaxCharacters", Boolean.TRUE)); + forum.setLimitedMinCharacters(JsonUtil.optBoolean(toolContentJSON, "limitedMinCharacters", Boolean.FALSE)); + forum.setLockWhenFinished(JsonUtil.optBoolean(toolContentJSON, "lockWhenFinished", Boolean.FALSE)); + forum.setMaxCharacters(JsonUtil.optInt(toolContentJSON, "maxCharacters", 5000)); // defaults to 5000 chars in the + // default entry in the db. + forum.setMaximumRate(JsonUtil.optInt(toolContentJSON, "maximumRate", 0)); + forum.setMaximumReply(JsonUtil.optInt(toolContentJSON, "maximumReply", 0)); + forum.setMinCharacters(JsonUtil.optInt(toolContentJSON, "minCharacters", 0)); + forum.setMinimumRate(JsonUtil.optInt(toolContentJSON, "minimumRate", 0)); + forum.setMinimumReply(JsonUtil.optInt(toolContentJSON, "minimumReply", 0)); forum.setNotifyLearnersOnForumPosting( - JsonUtil.opt(toolContentJSON, "notifyLearnersOnForumPosting", Boolean.FALSE)); + JsonUtil.optBoolean(toolContentJSON, "notifyLearnersOnForumPosting", Boolean.FALSE)); forum.setNotifyLearnersOnMarkRelease( - JsonUtil.opt(toolContentJSON, "notifyLearnersOnMarkRelease", Boolean.FALSE)); + JsonUtil.optBoolean(toolContentJSON, "notifyLearnersOnMarkRelease", Boolean.FALSE)); forum.setNotifyTeachersOnForumPosting( - JsonUtil.opt(toolContentJSON, "notifyTeachersOnForumPosting", Boolean.FALSE)); - forum.setReflectInstructions((String) JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, null)); - forum.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); + JsonUtil.optBoolean(toolContentJSON, "notifyTeachersOnForumPosting", Boolean.FALSE)); + forum.setReflectInstructions(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS)); + forum.setReflectOnActivity(JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); // submissionDeadline is set in monitoring // *******************************Handle user******************* @@ -1529,27 +1528,27 @@ // UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER); ForumUser forumUser = getUserByID(userID.longValue()); if (forumUser == null) { - forumUser = new ForumUser(userID.longValue(), toolContentJSON.getString("firstName"), - toolContentJSON.getString("lastName"), toolContentJSON.getString("loginName")); + forumUser = new ForumUser(userID.longValue(), JsonUtil.optString(toolContentJSON, "firstName"), + JsonUtil.optString(toolContentJSON, "lastName"), JsonUtil.optString(toolContentJSON, "loginName")); getForumUserDao().save(forumUser); } forum.setCreatedBy(forumUser); updateForum(forum); // **************************** Handle topic ********************* - JSONArray topics = toolContentJSON.getJSONArray("topics"); - for (int i = 0; i < topics.length(); i++) { - JSONObject msgData = (JSONObject) topics.get(i); + ArrayNode topics = JsonUtil.optArray(toolContentJSON, "topics"); + for (int i = 0; i < topics.size(); i++) { + ObjectNode msgData = (ObjectNode) topics.get(i); Message newMsg = new Message(); // newMsg.setAttachments(attachments); TODO newMsg.setCreatedBy(forumUser); newMsg.setCreated(updateDate); newMsg.setModifiedBy(null); newMsg.setUpdated(updateDate); - newMsg.setSubject(msgData.getString("subject")); - newMsg.setBody(msgData.getString("body")); + newMsg.setSubject(JsonUtil.optString(msgData, "subject")); + newMsg.setBody(JsonUtil.optString(msgData, "body")); newMsg.setForum(forum); newMsg.setHideFlag(false); // newMsg.setIsAnonymous(false); Does not appear on authoring interface Index: lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/web/actions/LearningAction.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/web/actions/LearningAction.java (.../LearningAction.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/web/actions/LearningAction.java (.../LearningAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -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.learningdesign.dto.ActivityPositionDTO; import org.lamsfoundation.lams.notebook.model.NotebookEntry; @@ -82,6 +79,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 */ @@ -175,7 +175,7 @@ if (sessionMapID != null) { sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID); } else { - sessionMap = new SessionMap(); + sessionMap = new SessionMap<>(); request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap); } @@ -230,14 +230,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()); @@ -482,11 +482,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); } @@ -766,9 +767,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); @@ -803,24 +803,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. */ @@ -918,11 +917,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 @@ -934,7 +933,7 @@ * Update a topic. */ public ActionForward updateTopicInline(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws PersistenceException, JSONException, IOException { + HttpServletResponse response) throws PersistenceException, IOException { forumService = getForumManager(); @@ -945,13 +944,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; } @@ -999,7 +998,7 @@ * Rates postings submitted by other learners. */ 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); @@ -1028,13 +1027,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_gmap/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_gmap/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_gmap/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -4,7 +4,7 @@ - + @@ -17,10 +17,12 @@ - + + + Index: lams_tool_images/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_images/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_images/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -4,7 +4,7 @@ - + @@ -14,13 +14,13 @@ - - + + - + Index: lams_tool_imscc/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_imscc/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_imscc/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -10,19 +10,19 @@ - - + + - + - + Index: lams_tool_kaltura/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_kaltura/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_kaltura/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -4,7 +4,7 @@ - + @@ -15,11 +15,13 @@ - + + + Index: lams_tool_kaltura/src/java/org/lamsfoundation/lams/tool/kaltura/web/actions/AuthoringAction.java =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_kaltura/src/java/org/lamsfoundation/lams/tool/kaltura/web/actions/AuthoringAction.java (.../AuthoringAction.java) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_kaltura/src/java/org/lamsfoundation/lams/tool/kaltura/web/actions/AuthoringAction.java (.../AuthoringAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -44,7 +44,7 @@ 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.ToolAccessMode; import org.lamsfoundation.lams.tool.kaltura.model.Kaltura; import org.lamsfoundation.lams.tool.kaltura.model.KalturaItem; @@ -225,7 +225,7 @@ * Stores uploaded entryId(s). */ public ActionForward addItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { String sessionMapID = WebUtil.readStrParam(request, KalturaConstants.ATTR_SESSION_MAP_ID); SessionMap sessionMap = (SessionMap) request.getSession() @@ -272,7 +272,7 @@ * Preview uploaded entryId. */ public ActionForward preview(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { // get back sessionMAP String sessionMapID = WebUtil.readStrParam(request, KalturaConstants.ATTR_SESSION_MAP_ID); Index: lams_tool_kaltura/src/java/org/lamsfoundation/lams/tool/kaltura/web/actions/LearningAction.java =================================================================== diff -u -rf4502360cd44d86d57b095aea5aef7ce663c8b61 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_kaltura/src/java/org/lamsfoundation/lams/tool/kaltura/web/actions/LearningAction.java (.../LearningAction.java) (revision f4502360cd44d86d57b095aea5aef7ce663c8b61) +++ lams_tool_kaltura/src/java/org/lamsfoundation/lams/tool/kaltura/web/actions/LearningAction.java (.../LearningAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -21,7 +21,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.tool.kaltura.web.actions; import java.io.IOException; @@ -45,8 +44,6 @@ import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.action.ActionRedirect; -import org.apache.tomcat.util.json.JSONException; -import org.apache.tomcat.util.json.JSONObject; import org.lamsfoundation.lams.learningdesign.dto.ActivityPositionDTO; import org.lamsfoundation.lams.notebook.model.NotebookEntry; import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; @@ -73,6 +70,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 Andrey Balan * @@ -98,7 +98,7 @@ initKalturaService(); // initialize Session Map - SessionMap sessionMap = new SessionMap(); + SessionMap sessionMap = new SessionMap<>(); String sessionMapId = sessionMap.getSessionID(); request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap); request.setAttribute(KalturaConstants.ATTR_SESSION_MAP_ID, sessionMapId); @@ -262,7 +262,7 @@ * Stores uploaded entryId(s). */ public ActionForward saveNewItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { initKalturaService(); String sessionMapID = WebUtil.readStrParam(request, KalturaConstants.ATTR_SESSION_MAP_ID); @@ -273,7 +273,7 @@ KalturaSession kalturaSession = service.getSessionBySessionId(toolSessionId); Kaltura kaltura = kalturaSession.getKaltura(); - TreeSet allItems = new TreeSet(new KalturaItemComparator()); + TreeSet allItems = new TreeSet<>(new KalturaItemComparator()); allItems.addAll(kaltura.getKalturaItems()); // check user can upload item @@ -315,10 +315,10 @@ item.setKalturaUid(kaltura.getUid()); service.saveKalturaItem(item); - JSONObject JSONObject = new JSONObject(); - JSONObject.put(KalturaConstants.PARAM_ITEM_UID, item.getUid()); + ObjectNode ObjectNode = JsonNodeFactory.instance.objectNode(); + ObjectNode.put(KalturaConstants.PARAM_ITEM_UID, item.getUid()); response.setContentType("application/json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(ObjectNode); return null; } @@ -386,7 +386,7 @@ * @throws ToolException */ public ActionForward rateItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { initKalturaService(); String sessionMapID = WebUtil.readStrParam(request, KalturaConstants.ATTR_SESSION_MAP_ID); @@ -404,11 +404,11 @@ KalturaItem item = (KalturaItem) sessionMap.get(KalturaConstants.ATTR_ITEM); item.setAverageRatingDto(averageRatingDto); - JSONObject JSONObject = new JSONObject(); - JSONObject.put("averageRating", averageRatingDto.getRating()); - JSONObject.put("numberOfVotes", averageRatingDto.getNumberOfVotes()); + ObjectNode ObjectNode = JsonNodeFactory.instance.objectNode(); + ObjectNode.put("averageRating", averageRatingDto.getRating()); + ObjectNode.put("numberOfVotes", averageRatingDto.getNumberOfVotes()); response.setContentType("application/json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(ObjectNode); return null; } @@ -522,7 +522,7 @@ private TreeSet getItems(ToolAccessMode mode, Kaltura kaltura, Long toolSessionId, Long userId) { // Create set of images, along with this filtering out items added by users from other groups - TreeSet items = new TreeSet(new KalturaItemComparator()); + TreeSet items = new TreeSet<>(new KalturaItemComparator()); items.addAll(service.getGroupItems(kaltura.getToolContentId(), toolSessionId, userId, mode.isTeacher())); for (KalturaItem item : items) { @@ -563,7 +563,7 @@ * Returns all comments done by teacher and learners of the specified group. */ private Set getGroupComments(KalturaItem item, Long sessionId, ToolAccessMode mode) { - TreeSet comments = new TreeSet(new KalturaCommentComparator()); + TreeSet comments = new TreeSet<>(new KalturaCommentComparator()); Set itemComments = item.getComments(); //only authored items can be seen by different groups Index: lams_tool_lamc/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_lamc/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_lamc/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -4,7 +4,7 @@ - + @@ -15,11 +15,13 @@ - + + + Index: lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/service/McService.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/service/McService.java (.../McService.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/service/McService.java (.../McService.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -48,12 +48,9 @@ import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.FillPatternType; 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.learningdesign.service.ExportToolContentException; @@ -111,6 +108,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 @@ -135,6 +136,7 @@ private IToolContentHandler mcToolContentHandler = null; private IExportToolContentService exportContentService; private ICoreNotebookService coreNotebookService; + private MessageService messageService; public McService() { @@ -936,7 +938,7 @@ HSSFWorkbook wb = new HSSFWorkbook(); HSSFCellStyle greenColor = wb.createCellStyle(); greenColor.setFillForegroundColor(IndexedColors.LIME.getIndex()); - greenColor.setFillPattern(CellStyle.SOLID_FOREGROUND); + greenColor.setFillPattern(FillPatternType.SOLID_FOREGROUND); Font whiteFont = wb.createFont(); whiteFont.setColor(IndexedColors.WHITE.getIndex()); whiteFont.setFontName(ExcelUtil.DEFAULT_FONT_NAME); @@ -1526,7 +1528,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); @@ -1537,7 +1539,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(); @@ -1802,17 +1804,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 @@ -1885,16 +1890,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(); @@ -1905,40 +1909,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, RestTags.ENABLE_CONFIDENCE_LEVELS, 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, RestTags.ENABLE_CONFIDENCE_LEVELS, 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 -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/web/action/McLearningAction.java (.../McLearningAction.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/web/action/McLearningAction.java (.../McLearningAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -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.notebook.model.NotebookEntry; import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; import org.lamsfoundation.lams.tool.exception.DataMissingException; @@ -67,6 +65,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 */ @@ -259,13 +260,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); } @@ -282,7 +284,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) { @@ -329,13 +331,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); @@ -388,7 +391,7 @@ String toolContentId = mcSession.getMcContent().getMcContentId().toString(); McContent mcContent = mcService.getMcContent(new Long(toolContentId)); - + String sessionMapID = mcLearningForm.getHttpSessionID(); request.setAttribute("sessionMapID", sessionMapID); @@ -492,15 +495,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); @@ -573,7 +578,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()); @@ -585,10 +590,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; } @@ -707,15 +712,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_laqa/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_laqa/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_laqa/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -4,7 +4,7 @@ - + @@ -15,12 +15,14 @@ - + + + + - Index: lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/service/QaService.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/service/QaService.java (.../QaService.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_tool_laqa/src/java/org/lamsfoundation/lams/tool/qa/service/QaService.java (.../QaService.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -21,7 +21,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.tool.qa.service; import java.util.ArrayList; @@ -39,9 +38,6 @@ import javax.servlet.http.HttpSession; 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.confidencelevel.ConfidenceLevelDTO; import org.lamsfoundation.lams.contentrepository.client.IToolContentHandler; import org.lamsfoundation.lams.events.IEventNotificationService; @@ -95,6 +91,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 Qa service. All business logics of Qa tool are implemented in this class. It translate the * request from presentation layer and perform approporiate database operation. @@ -575,8 +575,7 @@ @SuppressWarnings("unchecked") public void removeLearnerContent(Long toolContentId, Integer userId) throws ToolException { if (logger.isDebugEnabled()) { - logger - .debug("Removing Q&A answers for user ID " + userId + " and toolContentId " + toolContentId); + logger.debug("Removing Q&A answers for user ID " + userId + " and toolContentId " + toolContentId); } QaContent content = qaDAO.getQaByContentId(toolContentId); @@ -851,7 +850,7 @@ public boolean isCommentsEnabled(Long toolContentId) { return ratingService.isCommentsEnabled(toolContentId); } - + @Override public boolean isRatingsEnabled(QaContent qaContent) { //check if allow rate answers is ON and also that there is at least one non-comments rating criteria available @@ -871,7 +870,8 @@ @Override public List getRatingCriteriaDtos(Long contentId, Long toolSessionId, Collection itemIds, boolean isCommentsByOtherUsersRequired, Long userId) { - return ratingService.getRatingCriteriaDtos(contentId, toolSessionId, itemIds, isCommentsByOtherUsersRequired, userId); + return ratingService.getRatingCriteriaDtos(contentId, toolSessionId, itemIds, isCommentsByOtherUsersRequired, + userId); } @Override @@ -906,12 +906,12 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return getQaOutputFactory().getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public List getToolOutputs(String name, Long toolContentId) { return new ArrayList(); } - + @Override public List getConfidenceLevels(Long toolSessionId) { return null; @@ -986,10 +986,10 @@ public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } - + @Override public void auditLogStartEditingActivityInMonitor(long toolContentID) { - toolService.auditLogStartEditingActivityInMonitor(toolContentID); + toolService.auditLogStartEditingActivityInMonitor(toolContentID); } @Override @@ -1213,35 +1213,37 @@ if (learner == null) { return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_NOT_ATTEMPTED, null, null); } - + Date startDate = null; Date endDate = null; Set attempts = learner.getQaUsrResps(); for (QaUsrResp 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.isLearnerFinished()) + if (learner.isLearnerFinished()) { return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_COMPLETED, startDate, endDate); - else + } else { return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_ATTEMPTED, startDate, null); + } } // ****************** REST methods ************************* /** * Rest call to create a new Q&A content. Required fields in toolContentJSON: title, instructions, questions. The - * questions entry should be JSONArray containing JSON objects, which in turn must contain "questionText", + * questions entry should be ArrayNode containing JSON objects, which in turn must contain "questionText", * "displayOrder" and may also contain feedback and required (boolean) */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) { QaContent qa = new QaContent(); Date updateDate = new Date(); @@ -1251,26 +1253,26 @@ qa.setCreatedBy(userID.longValue()); qa.setQaContentId(toolContentID); - qa.setTitle(toolContentJSON.getString(RestTags.TITLE)); - qa.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); + qa.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE)); + qa.setInstructions(JsonUtil.optString(toolContentJSON, RestTags.INSTRUCTIONS)); qa.setDefineLater(false); - qa.setLockWhenFinished(JsonUtil.opt(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); - qa.setNoReeditAllowed(JsonUtil.opt(toolContentJSON, "noReeditAllowed", Boolean.FALSE)); - qa.setAllowRichEditor(JsonUtil.opt(toolContentJSON, RestTags.ALLOW_RICH_TEXT_EDITOR, Boolean.FALSE)); + qa.setLockWhenFinished(JsonUtil.optBoolean(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); + qa.setNoReeditAllowed(JsonUtil.optBoolean(toolContentJSON, "noReeditAllowed", Boolean.FALSE)); + qa.setAllowRichEditor(JsonUtil.optBoolean(toolContentJSON, RestTags.ALLOW_RICH_TEXT_EDITOR, Boolean.FALSE)); qa.setUseSelectLeaderToolOuput( - JsonUtil.opt(toolContentJSON, RestTags.USE_SELECT_LEADER_TOOL_OUTPUT, Boolean.FALSE)); - qa.setMinimumRates(JsonUtil.opt(toolContentJSON, RestTags.MINIMUM_RATES, 0)); - qa.setMaximumRates(JsonUtil.opt(toolContentJSON, RestTags.MAXIMUM_RATES, 0)); - qa.setShowOtherAnswers(JsonUtil.opt(toolContentJSON, "showOtherAnswers", Boolean.TRUE)); - qa.setUsernameVisible(JsonUtil.opt(toolContentJSON, "usernameVisible", Boolean.FALSE)); - qa.setAllowRateAnswers(JsonUtil.opt(toolContentJSON, "allowRateAnswers", Boolean.FALSE)); + JsonUtil.optBoolean(toolContentJSON, RestTags.USE_SELECT_LEADER_TOOL_OUTPUT, Boolean.FALSE)); + qa.setMinimumRates(JsonUtil.optInt(toolContentJSON, RestTags.MINIMUM_RATES, 0)); + qa.setMaximumRates(JsonUtil.optInt(toolContentJSON, RestTags.MAXIMUM_RATES, 0)); + qa.setShowOtherAnswers(JsonUtil.optBoolean(toolContentJSON, "showOtherAnswers", Boolean.TRUE)); + qa.setUsernameVisible(JsonUtil.optBoolean(toolContentJSON, "usernameVisible", Boolean.FALSE)); + qa.setAllowRateAnswers(JsonUtil.optBoolean(toolContentJSON, "allowRateAnswers", Boolean.FALSE)); qa.setNotifyTeachersOnResponseSubmit( - JsonUtil.opt(toolContentJSON, "notifyTeachersOnResponseSubmit", Boolean.FALSE)); - qa.setReflect(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - qa.setReflectionSubject(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, (String) null)); - qa.setQuestionsSequenced(JsonUtil.opt(toolContentJSON, "questionsSequenced", Boolean.FALSE)); + JsonUtil.optBoolean(toolContentJSON, "notifyTeachersOnResponseSubmit", Boolean.FALSE)); + qa.setReflect(JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); + qa.setReflectionSubject(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS)); + qa.setQuestionsSequenced(JsonUtil.optBoolean(toolContentJSON, "questionsSequenced", Boolean.FALSE)); // submissionDeadline is set in monitoring // qa.setMonitoringReportTitle(); Can't find this field in the database - assuming unused. @@ -1279,13 +1281,12 @@ saveOrUpdateQaContent(qa); // Questions - JSONArray questions = toolContentJSON.getJSONArray(RestTags.QUESTIONS); - for (int i = 0; i < questions.length(); i++) { - JSONObject questionData = (JSONObject) questions.get(i); - QaQueContent question = new QaQueContent(questionData.getString(RestTags.QUESTION_TEXT), - questionData.getInt(RestTags.DISPLAY_ORDER), JsonUtil.opt(questionData, "feedback", (String) null), - JsonUtil.opt(questionData, "required", Boolean.FALSE), - JsonUtil.opt(questionData, "minWordsLimit", 0), qa); + ArrayNode questions = JsonUtil.optArray(toolContentJSON, RestTags.QUESTIONS); + for (JsonNode questionData : questions) { + QaQueContent question = new QaQueContent(JsonUtil.optString(questionData, RestTags.QUESTION_TEXT), + JsonUtil.optInt(questionData, RestTags.DISPLAY_ORDER), JsonUtil.optString(questionData, "feedback"), + JsonUtil.optBoolean(questionData, "required", Boolean.FALSE), + JsonUtil.optInt(questionData, "minWordsLimit", 0), qa); saveOrUpdateQuestion(question); } Index: lams_tool_larsrc/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_larsrc/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_larsrc/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -3,7 +3,7 @@ - + @@ -15,13 +15,15 @@ - - + + - + + + Index: lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/service/ResourceServiceImpl.java =================================================================== diff -u -re2ab99460f405e52267d81c35ddb19b37edff7f3 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/service/ResourceServiceImpl.java (.../ResourceServiceImpl.java) (revision e2ab99460f405e52267d81c35ddb19b37edff7f3) +++ lams_tool_larsrc/src/java/org/lamsfoundation/lams/tool/rsrc/service/ResourceServiceImpl.java (.../ResourceServiceImpl.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -45,9 +45,6 @@ import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.struts.upload.FormFile; -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.NodeKey; import org.lamsfoundation.lams.contentrepository.client.IToolContentHandler; @@ -106,6 +103,10 @@ import org.lamsfoundation.lams.util.zipfile.ZipFileUtilException; import org.lamsfoundation.lams.web.util.AttributeNames; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * @author Dapeng.Ni */ @@ -218,7 +219,7 @@ } // add resource items from Authoring Resource resource = session.getResource(); - List items = new ArrayList(); + List items = new ArrayList<>(); items.addAll(resource.getResourceItems()); // add resource items from ResourceSession @@ -336,7 +337,7 @@ @Override public List getSummary(Long contentId) { - List groupList = new ArrayList(); + List groupList = new ArrayList<>(); Resource resource = resourceDao.getByContentId(contentId); @@ -350,14 +351,14 @@ group.setSessionId(session.getSessionId()); group.setSessionName(session.getSessionName()); - Set items = new TreeSet(new ResourceItemComparator()); + Set items = new TreeSet<>(new ResourceItemComparator()); // firstly, put all initial resource item into this group. items.addAll(resource.getResourceItems()); // add this session's resource items items.addAll(session.getResourceItems()); // item ids of items that could be rated. - List itemsToRate = new ArrayList(); + List itemsToRate = new ArrayList<>(); // get all item which is accessed by users in this session Map visitCountMap = resourceItemVisitDao.getSummary(contentId, session.getSessionId()); @@ -369,25 +370,26 @@ resourceItemDTO.setViewNumber(visitCountMap.get(item.getUid()).intValue()); } group.getItems().add(resourceItemDTO); - if ( item.isAllowRating() ) { + if (item.isAllowRating()) { itemsToRate.add(item.getUid()); } allowComments = allowComments || item.isAllowComments(); } - + List itemRatingDtos = null; - if ( itemsToRate.size() > 0 ) { - itemRatingDtos = ratingService.getRatingCriteriaDtos(contentId, session.getSessionId(), itemsToRate, false, -1L); + if (itemsToRate.size() > 0) { + itemRatingDtos = ratingService.getRatingCriteriaDtos(contentId, session.getSessionId(), itemsToRate, + false, -1L); group.setAllowRating(true); } else { group.setAllowRating(false); } - for (ResourceItemDTO item: group.getItems()) { + for (ResourceItemDTO item : group.getItems()) { if (item.isAllowRating()) { // find corresponding itemRatingDto - for ( ItemRatingDTO ratingDTO : itemRatingDtos ) { - if ( item.getItemUid().equals(ratingDTO.getItemId()) ) { + for (ItemRatingDTO ratingDTO : itemRatingDtos) { + if (item.getItemUid().equals(ratingDTO.getItemId())) { item.setRatingDTO(ratingDTO); break; } @@ -433,7 +435,7 @@ @Override public List getReflectList(Long contentId) { - List reflections = new LinkedList(); + List reflections = new LinkedList<>(); List sessionList = resourceSessionDao.getByContentId(contentId); for (ResourceSession session : sessionList) { @@ -469,7 +471,8 @@ user.setAccessDate(visit.getAccessDate()); user.setCompleteDate(visit.getCompleteDate()); Date timeTaken = ((visit.getCompleteDate() != null) && (visit.getAccessDate() != null)) - ? new Date(visit.getCompleteDate().getTime() - visit.getAccessDate().getTime()) : null; + ? new Date(visit.getCompleteDate().getTime() - visit.getAccessDate().getTime()) + : null; user.setTimeTaken(timeTaken); userList.add(user); } @@ -741,10 +744,10 @@ public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } - + @Override public void auditLogStartEditingActivityInMonitor(long toolContentID) { - toolService.auditLogStartEditingActivityInMonitor(toolContentID); + toolService.auditLogStartEditingActivityInMonitor(toolContentID); } // ******************************************************************************* @@ -817,13 +820,13 @@ item.setCreateBy(user); useRatings = useRatings || item.isAllowRating(); } - + Set criterias = toolContentObj.getRatingCriterias(); if (criterias != null) { for (LearnerItemRatingCriteria criteria : criterias) { criteria.setToolContentId(toolContentId); } - } + } resourceDao.saveObject(toolContentObj); } catch (ImportToolContentException e) { @@ -1041,9 +1044,9 @@ @Override public List getToolOutputs(String name, Long toolContentId) { - return new ArrayList(); + return new ArrayList<>(); } - + @Override public List getConfidenceLevels(Long toolSessionId) { return null; @@ -1062,8 +1065,9 @@ @Override public LearnerItemRatingCriteria createRatingCriteria(Long toolContentId) throws RatingException { List ratingCriterias = ratingService.getCriteriasByToolContentId(toolContentId); - if ( ratingCriterias == null || ratingCriterias.size() == 0 ) { - return ratingService.saveLearnerItemRatingCriteria(toolContentId, null, 1, RatingCriteria.RATING_STYLE_STAR, false, 0); + if (ratingCriterias == null || ratingCriterias.size() == 0) { + return ratingService.saveLearnerItemRatingCriteria(toolContentId, null, 1, RatingCriteria.RATING_STYLE_STAR, + false, 0); } else { return (LearnerItemRatingCriteria) ratingCriterias.get(0); } @@ -1073,9 +1077,10 @@ public int deleteRatingCriteria(Long toolContentId) { return ratingService.deleteAllRatingCriterias(toolContentId); } - + @Override - public List getRatingCriteriaDtos(Long toolContentId, Long toolSessionId, Collection itemIds, Long userId) { + public List getRatingCriteriaDtos(Long toolContentId, Long toolSessionId, Collection itemIds, + Long userId) { return ratingService.getRatingCriteriaDtos(toolContentId, toolSessionId, itemIds, false, userId); } @@ -1176,91 +1181,94 @@ if (learner == null) { return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_NOT_ATTEMPTED, null, null); } - + Object[] dates = resourceItemVisitDao.getDateRangeOfAccesses(learner.getUid(), toolSessionId); - if (learner.isSessionFinished()) - return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_COMPLETED, (Date)dates[0], (Date)dates[1]); - else - return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_ATTEMPTED,(Date) dates[0], null); + if (learner.isSessionFinished()) { + return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_COMPLETED, (Date) dates[0], (Date) dates[1]); + } else { + return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_ATTEMPTED, (Date) dates[0], null); + } } - + // ****************** REST methods ************************* /** * Used by the Rest calls to create content. Mandatory fields in toolContentJSON: title, instructions, resources, - * user fields firstName, lastName and loginName Resources must contain a JSONArray of JSONObject objects, which + * user fields firstName, lastName and loginName Resources must contain a ArrayNode of ObjectNode objects, which * have the following mandatory fields: title, description, type. If there are instructions for a resource, the - * instructions are a JSONArray of Strings. There should be at least one resource object in the resources array. + * instructions are a ArrayNode of Strings. There should be at least one resource object in the resources array. + * + * @throws IOException */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) + throws IOException { Date updateDate = new Date(); Resource resource = new Resource(); resource.setContentId(toolContentID); - resource.setTitle(toolContentJSON.getString(RestTags.TITLE)); - resource.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); + resource.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE)); + resource.setInstructions(JsonUtil.optString(toolContentJSON, RestTags.INSTRUCTIONS)); resource.setCreated(updateDate); - resource.setAllowAddFiles(JsonUtil.opt(toolContentJSON, "allowAddFiles", Boolean.FALSE)); - resource.setAllowAddUrls(JsonUtil.opt(toolContentJSON, "allowAddUrls", Boolean.FALSE)); - resource.setLockWhenFinished(JsonUtil.opt(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); - resource.setMiniViewResourceNumber(JsonUtil.opt(toolContentJSON, "minViewResourceNumber", 0)); + resource.setAllowAddFiles(JsonUtil.optBoolean(toolContentJSON, "allowAddFiles", Boolean.FALSE)); + resource.setAllowAddUrls(JsonUtil.optBoolean(toolContentJSON, "allowAddUrls", Boolean.FALSE)); + resource.setLockWhenFinished(JsonUtil.optBoolean(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); + resource.setMiniViewResourceNumber(JsonUtil.optInt(toolContentJSON, "minViewResourceNumber", 0)); resource.setNotifyTeachersOnAssigmentSumbit( - JsonUtil.opt(toolContentJSON, "notifyTeachersOnAssigmentSubmit", Boolean.FALSE)); + JsonUtil.optBoolean(toolContentJSON, "notifyTeachersOnAssigmentSubmit", Boolean.FALSE)); resource.setNotifyTeachersOnAssigmentSumbit( - JsonUtil.opt(toolContentJSON, "notifyTeachersOnFileUpload", Boolean.FALSE)); - resource.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - resource.setReflectInstructions(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, (String) null)); - resource.setRunAuto(JsonUtil.opt(toolContentJSON, "runAuto", Boolean.FALSE)); + JsonUtil.optBoolean(toolContentJSON, "notifyTeachersOnFileUpload", Boolean.FALSE)); + resource.setReflectOnActivity( + JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); + resource.setReflectInstructions(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS)); + resource.setRunAuto(JsonUtil.optBoolean(toolContentJSON, "runAuto", Boolean.FALSE)); resource.setContentInUse(false); resource.setDefineLater(false); ResourceUser resourceUser = getUserByIDAndContent(userID.longValue(), toolContentID); if (resourceUser == null) { resourceUser = new ResourceUser(); - resourceUser.setFirstName(toolContentJSON.getString("firstName")); - resourceUser.setLastName(toolContentJSON.getString("lastName")); - resourceUser.setLoginName(toolContentJSON.getString("loginName")); + resourceUser.setFirstName(JsonUtil.optString(toolContentJSON, "firstName")); + resourceUser.setLastName(JsonUtil.optString(toolContentJSON, "lastName")); + resourceUser.setLoginName(JsonUtil.optString(toolContentJSON, "loginName")); // resourceUser.setResource(content); } resource.setCreatedBy(resourceUser); // **************************** Handle topic ********************* - JSONArray resources = toolContentJSON.getJSONArray("resources"); + ArrayNode resources = JsonUtil.optArray(toolContentJSON, "resources"); Set itemList = new LinkedHashSet(); - for (int i = 0; i < resources.length(); i++) { - JSONObject itemData = (JSONObject) resources.get(i); + for (JsonNode itemData : resources) { ResourceItem item = new ResourceItem(); - item.setTitle(itemData.getString("title")); - item.setType((short) itemData.getInt("type")); + item.setTitle(JsonUtil.optString(itemData, "title")); + item.setType(JsonUtil.optInt(itemData, "type").shortValue()); item.setCreateBy(resourceUser); item.setCreateDate(updateDate); item.setComplete(false); item.setCreateByAuthor(true); item.setHide(false); - item.setOrderId(itemData.getInt(RestTags.DISPLAY_ORDER)); + item.setOrderId(JsonUtil.optInt(itemData, RestTags.DISPLAY_ORDER)); - item.setDescription(JsonUtil.opt(itemData, "description", (String) null)); - item.setFileName(JsonUtil.opt(itemData, "name", (String) null)); - item.setFileType(JsonUtil.opt(itemData, "fileType", (String) null)); + item.setDescription(JsonUtil.optString(itemData, "description")); + item.setFileName(JsonUtil.optString(itemData, "name")); + item.setFileType(JsonUtil.optString(itemData, "fileType")); item.setFileUuid(JsonUtil.optLong(itemData, "crUuid")); item.setFileVersionId(JsonUtil.optLong(itemData, "crVersionId")); - item.setImsSchema(JsonUtil.opt(itemData, "imsSchema", (String) null)); - item.setOrganizationXml(JsonUtil.opt(itemData, "organizationXml", (String) null)); - item.setOpenUrlNewWindow(JsonUtil.opt(itemData, "openUrlNewWindow", Boolean.FALSE)); - item.setUrl(JsonUtil.opt(itemData, "url", (String) null)); + item.setImsSchema(JsonUtil.optString(itemData, "imsSchema")); + item.setOrganizationXml(JsonUtil.optString(itemData, "organizationXml")); + item.setOpenUrlNewWindow(JsonUtil.optBoolean(itemData, "openUrlNewWindow", Boolean.FALSE)); + item.setUrl(JsonUtil.optString(itemData, "url")); - JSONArray instructionStrings = itemData.getJSONArray("instructions"); - if ((instructionStrings != null) && (instructionStrings.length() > 0)) { + ArrayNode instructionStrings = JsonUtil.optArray(itemData, "instructions"); + if ((instructionStrings != null) && (instructionStrings.size() > 0)) { Set instructions = new LinkedHashSet(); - for (int j = 0; j < instructionStrings.length(); j++) { + for (int j = 0; j < instructionStrings.size(); j++) { ResourceItemInstruction rii = new ResourceItemInstruction(); - rii.setDescription(instructionStrings.getString(j)); + rii.setDescription(instructionStrings.get(j).asText(null)); rii.setSequenceId(j); instructions.add(rii); } @@ -1269,7 +1277,7 @@ // TODO files - need to save it somehow, validate the file size, etc. Needed for websites, files & LO if ((item.getFileName() != null) || (item.getFileUuid() != null)) { - throw new JSONException( + throw new IOException( "Only URLS supported via REST interface currently - files and learning objects are not supported."); } @@ -1282,6 +1290,7 @@ } + @Override public void evict(Object object) { resourceDao.releaseFromCache(object); } Index: lams_tool_leader/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_leader/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_leader/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -4,7 +4,7 @@ - + @@ -15,12 +15,14 @@ - + - + + + Index: lams_tool_leader/src/java/org/lamsfoundation/lams/tool/leaderselection/service/LeaderselectionService.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_leader/src/java/org/lamsfoundation/lams/tool/leaderselection/service/LeaderselectionService.java (.../LeaderselectionService.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_tool_leader/src/java/org/lamsfoundation/lams/tool/leaderselection/service/LeaderselectionService.java (.../LeaderselectionService.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -31,8 +31,6 @@ import java.util.SortedMap; import org.apache.log4j.Logger; -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.learningdesign.service.ExportToolContentException; @@ -62,7 +60,10 @@ import org.lamsfoundation.lams.tool.service.ILamsToolService; import org.lamsfoundation.lams.usermanagement.User; import org.lamsfoundation.lams.usermanagement.dto.UserDTO; +import org.lamsfoundation.lams.util.JsonUtil; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * An implementation of the ILeaderselectionService interface. * @@ -148,7 +149,7 @@ public List getToolOutputs(String name, Long toolContentId) { return new ArrayList<>(); } - + @Override public List getConfidenceLevels(Long toolSessionId) { return null; @@ -322,7 +323,7 @@ /* ********** ILeaderselectionService Methods ********************************* */ @Override - public boolean setGroupLeader(Long userUid, Long toolSessionId) throws JSONException, IOException { + public boolean setGroupLeader(Long userUid, Long toolSessionId) throws IOException { if ((userUid == null) || (toolSessionId == null)) { return false; } @@ -437,7 +438,7 @@ public LeaderselectionUser getUserByUserIdAndSessionId(Long userId, Long toolSessionId) { return leaderselectionUserDAO.getByUserIdAndSessionId(userId, toolSessionId); } - + @Override public LeaderselectionUser getUserByUserIdAndContentId(Long userId, Long toolContentId) { return leaderselectionUserDAO.getByUserIdAndContentId(userId, toolContentId); @@ -569,14 +570,13 @@ * Rest call to create a new Learner Selection content. Required fields in toolContentJSON: "title", "instructions". */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) { Date updateDate = new Date(); Leaderselection leaderselection = new Leaderselection(); leaderselection.setToolContentId(toolContentID); - leaderselection.setTitle(toolContentJSON.getString(RestTags.TITLE)); - leaderselection.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); + leaderselection.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE)); + leaderselection.setInstructions(JsonUtil.optString(toolContentJSON, RestTags.INSTRUCTIONS)); leaderselection.setCreateBy(userID.longValue()); leaderselection.setCreateDate(updateDate); leaderselection.setUpdateDate(updateDate); Index: lams_tool_leader/src/java/org/lamsfoundation/lams/tool/leaderselection/web/actions/LearningAction.java =================================================================== diff -u -rf4502360cd44d86d57b095aea5aef7ce663c8b61 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_leader/src/java/org/lamsfoundation/lams/tool/leaderselection/web/actions/LearningAction.java (.../LearningAction.java) (revision f4502360cd44d86d57b095aea5aef7ce663c8b61) +++ lams_tool_leader/src/java/org/lamsfoundation/lams/tool/leaderselection/web/actions/LearningAction.java (.../LearningAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -34,7 +34,7 @@ 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.ToolAccessMode; import org.lamsfoundation.lams.tool.ToolSessionManager; import org.lamsfoundation.lams.tool.exception.DataMissingException; @@ -125,7 +125,7 @@ * @throws JSONException */ public ActionForward becomeLeader(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, JSONException { + HttpServletResponse response) throws IOException { initService(); Long toolSessionId = new Long(request.getParameter(AttributeNames.PARAM_TOOL_SESSION_ID)); LeaderselectionSession session = service.getSessionBySessionId(toolSessionId); Index: lams_tool_mindmap/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_mindmap/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_mindmap/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -9,17 +9,20 @@ - + - + - + + + + - + Index: lams_tool_mindmap/src/java/org/lamsfoundation/lams/tool/mindmap/service/MindmapService.java =================================================================== diff -u -r1e5b385c02e618c2bbaafb6321e1bbf78473cd2b -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_mindmap/src/java/org/lamsfoundation/lams/tool/mindmap/service/MindmapService.java (.../MindmapService.java) (revision 1e5b385c02e618c2bbaafb6321e1bbf78473cd2b) +++ lams_tool_mindmap/src/java/org/lamsfoundation/lams/tool/mindmap/service/MindmapService.java (.../MindmapService.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -21,7 +21,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.tool.mindmap.service; import java.util.ArrayList; @@ -33,8 +32,6 @@ import java.util.SortedMap; import org.apache.log4j.Logger; -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.learningdesign.service.ExportToolContentException; @@ -78,8 +75,9 @@ import org.lamsfoundation.lams.util.JsonUtil; import org.lamsfoundation.lams.util.MessageService; +import com.fasterxml.jackson.databind.node.ObjectNode; 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; /** @@ -91,7 +89,7 @@ private static final int NODE_TEXT_LENGTH = 100; // node_text column in the database is varchar(100) private static Logger logger = Logger.getLogger(MindmapService.class.getName()); - private final XStream xstream = new XStream(new SunUnsafeReflectionProvider()); + private final XStream xstream = new XStream(new StaxDriver()); private IMindmapDAO mindmapDAO = null; private IMindmapSessionDAO mindmapSessionDAO = null; @@ -167,12 +165,12 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return getMindmapOutputFactory().getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public List getToolOutputs(String name, Long toolContentId) { - return new ArrayList(); + return new ArrayList<>(); } - + @Override public List getConfidenceLevels(Long toolSessionId) { return null; @@ -333,12 +331,12 @@ int edit; if ( isAuthor ){ - edit = 1; + edit = 1; } else if ( isMonitor || isUserLocked || mindmapUser == null) { edit = 0; - } else { + } else { edit = mindmapUser.equals(mindmapNode.getUser()) ? 1 : 0; - } + } NodeModel nodeModel = new NodeModel(new NodeConceptModel(mindmapNode.getUniqueId(), mindmapNode.getText(), mindmapNode.getColor(), mindmapUserName, edit)); @@ -427,13 +425,13 @@ return; } - List nodesToDelete = new LinkedList(); + List nodesToDelete = new LinkedList<>(); for (MindmapSession session : (Set) mindmap.getMindmapSessions()) { List nodes = mindmapNodeDAO.getMindmapNodesBySessionIdAndUserId(session.getSessionId(), userId.longValue()); for (MindmapNode node : nodes) { - List descendants = new LinkedList(); + List descendants = new LinkedList<>(); if ((node.getUser() != null) && node.getUser().getUserId().equals(userId.longValue()) && !nodesToDelete.contains(node) && userOwnsChildrenNodes(node, userId.longValue(), descendants)) { @@ -830,10 +828,10 @@ public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } - + @Override public void auditLogStartEditingActivityInMonitor(long toolContentID) { - toolService.auditLogStartEditingActivityInMonitor(toolContentID); + toolService.auditLogStartEditingActivityInMonitor(toolContentID); } public void setMindmapNodeDAO(IMindmapNodeDAO mindmapNodeDAO) { @@ -895,7 +893,6 @@ @Override public MindmapNode getMindmapNodeByUniqueIdSessionId(Long uniqueId, Long mindmapId, Long sessionId) { return mindmapNodeDAO.getMindmapNodeByUniqueIdSessionId(uniqueId, mindmapId, sessionId); - } @Override @@ -984,22 +981,21 @@ * (default false), reflectOnActivity (default false), reflectInstructions */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) { Mindmap content = new Mindmap(); Date updateDate = new Date(); content.setToolContentId(toolContentID); content.setCreateDate(updateDate); content.setUpdateDate(updateDate); - content.setTitle(toolContentJSON.getString(RestTags.TITLE)); - content.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); + content.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE)); + content.setInstructions(JsonUtil.optString(toolContentJSON, RestTags.INSTRUCTIONS)); content.setContentInUse(false); content.setDefineLater(false); - content.setReflectInstructions((String) JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, null)); - content.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - content.setLockOnFinished(JsonUtil.opt(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); - content.setMultiUserMode(JsonUtil.opt(toolContentJSON, "multiUserMode", Boolean.FALSE)); + content.setReflectInstructions(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS)); + content.setReflectOnActivity(JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); + content.setLockOnFinished(JsonUtil.optBoolean(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); + content.setMultiUserMode(JsonUtil.optBoolean(toolContentJSON, "multiUserMode", Boolean.FALSE)); // createdBy and submissionDeadline are null in the database using the standard authoring module // submissionDeadline is set in monitoring Index: lams_tool_mindmap/src/java/org/lamsfoundation/lams/tool/mindmap/web/actions/AuthoringAction.java =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_mindmap/src/java/org/lamsfoundation/lams/tool/mindmap/web/actions/AuthoringAction.java (.../AuthoringAction.java) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_mindmap/src/java/org/lamsfoundation/lams/tool/mindmap/web/actions/AuthoringAction.java (.../AuthoringAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -21,7 +21,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.tool.mindmap.web.actions; import java.io.IOException; @@ -35,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.JSONException; -import org.apache.tomcat.util.json.JSONObject; import org.lamsfoundation.lams.tool.ToolAccessMode; import org.lamsfoundation.lams.tool.mindmap.dto.RootJSON; import org.lamsfoundation.lams.tool.mindmap.model.Mindmap; @@ -54,6 +51,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 Ruslan Kazakov * @version 1.0.1 @@ -116,21 +116,20 @@ // while we are editing. This flag is released when updateContent is called. mindmap.setDefineLater(true); mindmapService.saveOrUpdateMindmap(mindmap); - + //audit log the teacher has started editing activity in monitor mindmapService.auditLogStartEditingActivityInMonitor(toolContentID); } /* Mindmap Attributes */ request.setAttribute("mindmapId", mindmap.getUid()); - + // Set up the authForm. AuthoringForm authForm = (AuthoringForm) form; updateAuthForm(authForm, mindmap); // Set up sessionMap - SessionMap map = createSessionMap(mindmap, mode, contentFolderID, - toolContentID); + SessionMap map = createSessionMap(mindmap, mode, contentFolderID, toolContentID); authForm.setSessionMapID(map.getSessionID()); // add the sessionMap to HTTPSession. @@ -144,7 +143,7 @@ * Returns the serialized XML of the Mindmap Nodes from Database */ public ActionForward setMindmapContentJSON(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { // set up mindmapService if (mindmapService == null) { @@ -164,8 +163,8 @@ NodeModel currentNodeModel = mindmapService.getMindmapXMLFromDatabase(rootMindmapNode.getNodeId(), mindmapId, rootNodeModel, null, false, true, false); - JSONObject jsonObject = new JSONObject(); - jsonObject.put("mindmap", new RootJSON(currentNodeModel, false)); + ObjectNode jsonObject = JsonNodeFactory.instance.objectNode(); + jsonObject.set("mindmap", new RootJSON(currentNodeModel, false)); response.setContentType("application/x-json;charset=utf-8"); response.getWriter().print(jsonObject.toString()); @@ -177,9 +176,11 @@ /** * Saves Mindmap Nodes to Database + * + * @throws IOException */ public ActionForward updateContent(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException { + HttpServletResponse response) throws IOException { // get authForm and session map. AuthoringForm authForm = (AuthoringForm) form; SessionMap map = getSessionMap(request, authForm); @@ -210,14 +211,11 @@ String mindmapContent = authForm.getMindmapContent(); NodeModel rootNodeModel = RootJSON.toNodeModel(mindmapContent); - if ( rootNodeModel == null ) { + if (rootNodeModel == null) { String error = new StringBuilder("Unable to save mindmap for authoring. User:") - .append(mindmapUser.getLoginName()) - .append("("+mindmapUser.getUserId()) - .append("). No root node. JSON: ") - .append(mindmapContent) - .toString(); - throw new JSONException(error); + .append(mindmapUser.getLoginName()).append("(" + mindmapUser.getUserId()) + .append("). No root node. JSON: ").append(mindmapContent).toString(); + throw new IOException(error); } NodeConceptModel nodeConceptModel = rootNodeModel.getConcept(); Index: lams_tool_mindmap/src/java/org/lamsfoundation/lams/tool/mindmap/web/actions/LearningAction.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_mindmap/src/java/org/lamsfoundation/lams/tool/mindmap/web/actions/LearningAction.java (.../LearningAction.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_tool_mindmap/src/java/org/lamsfoundation/lams/tool/mindmap/web/actions/LearningAction.java (.../LearningAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -38,8 +38,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.notebook.model.NotebookEntry; import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; import org.lamsfoundation.lams.tool.ToolAccessMode; @@ -66,11 +64,16 @@ import org.lamsfoundation.lams.util.Configuration; import org.lamsfoundation.lams.util.ConfigurationKeys; import org.lamsfoundation.lams.util.DateUtil; +import org.lamsfoundation.lams.util.JsonUtil; 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 com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * @author Ruslan Kazakov * @version 1.0.1 @@ -86,11 +89,10 @@ private static Logger log = Logger.getLogger(LearningAction.class); private static final boolean MODE_OPTIONAL = false; private IMindmapService mindmapService; - + private static final String REQUEST_JSON_TYPE = "type"; // Expected to be int: 0 - delete; 1 - create node; 2 - change color; 3 - change text private static final String REQUEST_JSON_REQUEST_ID = "requestId"; // Expected to be long private static final String REQUEST_JSON_PARENT_NODE_ID = "parentId"; // Expected to be long - /** * Default action on page load. Clones Mindmap Nodes for each Learner in single-user mode. Uses shared (runtime @@ -273,42 +275,45 @@ * @param request * @param response * @return null - * @throws JSONException + * @throws IOException + * @throws JsonProcessingException + * @throws JSONException */ @SuppressWarnings("rawtypes") public ActionForward notifyServerActionJSON(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException { - + HttpServletResponse response) throws JsonProcessingException, IOException { Long userId = WebUtil.readLongParam(request, "userId", false); Long mindmapId = WebUtil.readLongParam(request, "mindmapId", false); Long toolSessionId = WebUtil.readLongParam(request, "sessionId", false); String requestAction = WebUtil.readStrParam(request, "actionJSON", false); MindmapSession mindmapSession = mindmapService.getSessionBySessionId(toolSessionId); - JSONObject notifyRequest = new JSONObject(requestAction); - int requestType = notifyRequest.getInt(REQUEST_JSON_TYPE); - + ObjectNode notifyRequest = JsonUtil.readObject(requestAction); + int requestType = JsonUtil.optInt(notifyRequest, REQUEST_JSON_TYPE); + MindmapRequest mindmapRequest = null; - if ( notifyRequest.has(REQUEST_JSON_REQUEST_ID)) { + if (notifyRequest.has(REQUEST_JSON_REQUEST_ID)) { Long lastActionId = WebUtil.readLongParam(request, "lastActionId", false); - mindmapRequest = mindmapService.getRequestByUniqueId(notifyRequest.getLong(REQUEST_JSON_REQUEST_ID), userId, mindmapId, lastActionId); + mindmapRequest = mindmapService.getRequestByUniqueId( + JsonUtil.optLong(notifyRequest, REQUEST_JSON_REQUEST_ID), userId, mindmapId, lastActionId); } NotifyResponseJSON notifyResponse = null; - + MindmapUser currentUser = mindmapService.getUserByUID(userId); - if ( currentUser == null || ( mindmapSession.getMindmap().isLockOnFinished() && currentUser.isFinishedActivity() ) ) { + if (currentUser == null + || (mindmapSession.getMindmap().isLockOnFinished() && currentUser.isFinishedActivity())) { notifyResponse = new NotifyResponseJSON(0, null, null); - } - + } + // if request wasn't created before, create it else if (mindmapRequest == null) { // getting node to which changes will be applied MindmapNode mindmapNode = null; if (notifyRequest.has(IdeaJSON.MAPJS_JSON_ID_KEY) && requestType != 1) { mindmapNode = mindmapService.getMindmapNodeByUniqueIdSessionId( - notifyRequest.getLong(IdeaJSON.MAPJS_JSON_ID_KEY), mindmapId, toolSessionId); + JsonUtil.optLong(notifyRequest, IdeaJSON.MAPJS_JSON_ID_KEY), mindmapId, toolSessionId); if (mindmapNode == null) { LearningAction.log.error("notifyServerAction(): Error finding node!"); return null; @@ -325,9 +330,10 @@ if ((childNodes == null) || (childNodes.size() == 0)) // check if node has any children { - mindmapService.deleteNodeByUniqueMindmapUser(mindmapNode.getUniqueId(), mindmapId, userId, mindmapSession.getUid()); - mindmapRequest = saveMindmapRequestJSON(mindmapRequest, requestType, null, mindmapNode.getUniqueId(), userId, - mindmapId, null, toolSessionId); + mindmapService.deleteNodeByUniqueMindmapUser(mindmapNode.getUniqueId(), mindmapId, userId, + mindmapSession.getUid()); + mindmapRequest = saveMindmapRequestJSON(mindmapRequest, requestType, null, + mindmapNode.getUniqueId(), userId, mindmapId, null, toolSessionId); notifyResponse = new NotifyResponseJSON(1, mindmapRequest.getGlobalId(), null); } else { notifyResponse = new NotifyResponseJSON(0, null, null); @@ -338,38 +344,41 @@ } // create node else if (requestType == 1) { - // no checking... users can create nodes everywhere. - + // no checking... users can create nodes everywhere. + // node unique ID - keep the biggest out of (next database value, client node). this ensures // that deletions don't go back and fill holes with nodes that may conflict with something on a client. - Long uniqueId = mindmapService.getNodeLastUniqueIdByMindmapUidSessionId(mindmapId, toolSessionId) + 1; - Long childIdFromRequest = notifyRequest.getLong(IdeaJSON.MAPJS_JSON_ID_KEY); - if ( childIdFromRequest.longValue() > uniqueId.longValue() ) + Long uniqueId = mindmapService.getNodeLastUniqueIdByMindmapUidSessionId(mindmapId, toolSessionId) + 1; + Long childIdFromRequest = JsonUtil.optLong(notifyRequest, IdeaJSON.MAPJS_JSON_ID_KEY); + if (childIdFromRequest.longValue() > uniqueId.longValue()) { uniqueId = childIdFromRequest; + } - Long parentNodeId = notifyRequest.getLong(REQUEST_JSON_PARENT_NODE_ID); - MindmapNode parentNode = mindmapService.getMindmapNodeByUniqueIdSessionId(parentNodeId, mindmapId, toolSessionId); + Long parentNodeId = JsonUtil.optLong(notifyRequest, REQUEST_JSON_PARENT_NODE_ID); + MindmapNode parentNode = mindmapService.getMindmapNodeByUniqueIdSessionId(parentNodeId, mindmapId, + toolSessionId); if (parentNode == null) { - LearningAction.log.error("notifyServerAction(): Unable to find parent node: "+parentNodeId+" toolSessionId "+toolSessionId); + LearningAction.log.error("notifyServerAction(): Unable to find parent node: " + parentNodeId + + " toolSessionId " + toolSessionId); } - mindmapService.saveMindmapNode(null, parentNode, uniqueId, - notifyRequest.optString(IdeaJSON.MAPJS_JSON_TITLE_KEY), - notifyRequest.optString(IdeaJSON.MAPJS_JSON_BACKGROUND_COLOR_KEY), mindmapService.getUserByUID(userId), - mindmapService.getMindmapByUid(mindmapId), mindmapSession); + mindmapService.saveMindmapNode(null, parentNode, uniqueId, + JsonUtil.optString(notifyRequest, IdeaJSON.MAPJS_JSON_TITLE_KEY), + JsonUtil.optString(notifyRequest, IdeaJSON.MAPJS_JSON_BACKGROUND_COLOR_KEY), + mindmapService.getUserByUID(userId), mindmapService.getMindmapByUid(mindmapId), mindmapSession); - mindmapRequest = saveMindmapRequestJSON(mindmapRequest, requestType, null, parentNodeId, userId, mindmapId, - uniqueId, toolSessionId); + mindmapRequest = saveMindmapRequestJSON(mindmapRequest, requestType, null, parentNodeId, userId, + mindmapId, uniqueId, toolSessionId); notifyResponse = new NotifyResponseJSON(1, mindmapRequest.getGlobalId(), uniqueId); } // change color else if (requestType == 2) { if (mindmapNode.getUser() == mindmapService.getUserByUID(userId)) { - mindmapNode.setColor(notifyRequest.optString(IdeaJSON.MAPJS_JSON_BACKGROUND_COLOR_KEY)); + mindmapNode.setColor(JsonUtil.optString(notifyRequest, IdeaJSON.MAPJS_JSON_BACKGROUND_COLOR_KEY)); mindmapNode.setUser(mindmapService.getUserByUID(userId)); mindmapService.saveOrUpdateMindmapNode(mindmapNode); - mindmapRequest = saveMindmapRequestJSON(mindmapRequest, requestType, null, mindmapNode.getUniqueId(), userId, - mindmapId, null, toolSessionId); + mindmapRequest = saveMindmapRequestJSON(mindmapRequest, requestType, null, + mindmapNode.getUniqueId(), userId, mindmapId, null, toolSessionId); notifyResponse = new NotifyResponseJSON(1, mindmapRequest.getGlobalId(), null); } else { notifyResponse = new NotifyResponseJSON(0, null, null); @@ -378,11 +387,11 @@ // change text else if (requestType == 3) { if (mindmapNode.getUser() == mindmapService.getUserByUID(userId)) { - mindmapNode.setText(notifyRequest.optString(IdeaJSON.MAPJS_JSON_TITLE_KEY)); + mindmapNode.setText(JsonUtil.optString(notifyRequest, IdeaJSON.MAPJS_JSON_TITLE_KEY)); mindmapNode.setUser(mindmapService.getUserByUID(userId)); mindmapService.saveOrUpdateMindmapNode(mindmapNode); - mindmapRequest = saveMindmapRequestJSON(mindmapRequest, requestType, null, mindmapNode.getUniqueId(), userId, - mindmapId, null, toolSessionId); + mindmapRequest = saveMindmapRequestJSON(mindmapRequest, requestType, null, + mindmapNode.getUniqueId(), userId, mindmapId, null, toolSessionId); notifyResponse = new NotifyResponseJSON(1, mindmapRequest.getGlobalId(), null); } else { notifyResponse = new NotifyResponseJSON(0, null, null); @@ -440,12 +449,12 @@ * @param request * @param response * @return null - * @throws JSONException - * @throws IOException + * @throws JSONException + * @throws IOException */ @SuppressWarnings("rawtypes") public ActionForward setMindmapContentJSON(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { // set up mindmapService if (mindmapService == null) { @@ -498,8 +507,8 @@ mindmapId, rootNodeModel, mindmapUser, monitoring, false, mindmap.isLockOnFinished() && mindmapUser.isFinishedActivity()); - JSONObject jsonObject = new JSONObject(); - jsonObject.put("mindmap", new RootJSON(currentNodeModel, mindmap.isMultiUserMode())); + ObjectNode jsonObject = JsonNodeFactory.instance.objectNode(); + jsonObject.set("mindmap", new RootJSON(currentNodeModel, mindmap.isMultiUserMode())); // adding lastActionId if (mindmap.isMultiUserMode()) { Long lastActionId = mindmapService.getLastGlobalIdByMindmapId(mindmap.getUid(), toolSessionId); @@ -513,9 +522,8 @@ return null; } - public ActionForward saveLastMindmapChanges(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { Long userId = WebUtil.readLongParam(request, "userId", false); Long toolContentId = WebUtil.readLongParam(request, "mindmapId", false); @@ -530,7 +538,7 @@ // getting JSON from Mindmup String mindmapContent = WebUtil.readStrParam(request, "content", false); Long rootNodeId = saveMapJsJSON(mindmap, mindmapUser, mindmapContent, mindmapSession); - responseJSON = new NotifyResponseJSON( rootNodeId != null ? 1 : 0, null, rootNodeId); + responseJSON = new NotifyResponseJSON(rootNodeId != null ? 1 : 0, null, rootNodeId); } else { responseJSON = new NotifyResponseJSON(0, null, 0L); } @@ -541,23 +549,17 @@ } private Long saveMapJsJSON(Mindmap mindmap, MindmapUser mindmapUser, String mindmapContent, - MindmapSession mindmapSession) throws JSONException { - + MindmapSession mindmapSession) throws IOException { + NodeModel rootNodeModel = RootJSON.toNodeModel(mindmapContent); - if ( rootNodeModel == null ) { + if (rootNodeModel == null) { String error = new StringBuilder("Unable to save mindmap for session:") - .append(mindmapSession.getSessionName()) - .append("(") - .append(mindmapSession.getSessionId()) - .append(") user:") - .append(mindmapUser.getLoginName()) - .append("("+mindmapUser.getUserId()) - .append("). No root node. JSON: ") - .append(mindmapContent) - .toString(); - throw new JSONException(error); + .append(mindmapSession.getSessionName()).append("(").append(mindmapSession.getSessionId()) + .append(") user:").append(mindmapUser.getLoginName()).append("(" + mindmapUser.getUserId()) + .append("). No root node. JSON: ").append(mindmapContent).toString(); + throw new IOException(error); } - + NodeConceptModel nodeConceptModel = rootNodeModel.getConcept(); List branches = rootNodeModel.getBranch(); @@ -579,7 +581,7 @@ nodesToDeleteCondition += mindmapService.getNodesToDeleteCondition() + " and mindmap_id = " + mindmap.getUid() + " and user_id = " + mindmapUser.getUid(); mindmapService.deleteNodes(nodesToDeleteCondition); - + return rootMindmapNode.getNodeId(); } @@ -612,10 +614,11 @@ * @param request * @param response * @return - * @throws JSONException + * @throws IOException + * @throws JSONException */ public ActionForward reflect(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException { + HttpServletResponse response) throws IOException { LearningForm learningForm = (LearningForm) form; @@ -660,10 +663,11 @@ * @param request * @param response * @return null - * @throws JSONException + * @throws IOException + * @throws JSONException */ public ActionForward finishActivity(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException { + HttpServletResponse response) throws IOException { Long toolSessionID = WebUtil.readLongParam(request, "toolSessionID"); MindmapUser mindmapUser = getCurrentUser(toolSessionID); Index: lams_tool_nb/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_nb/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_nb/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -4,7 +4,7 @@ - + @@ -15,6 +15,8 @@ - + + + Index: lams_tool_nb/src/java/org/lamsfoundation/lams/tool/noticeboard/service/NoticeboardService.java =================================================================== diff -u -r02b9b123b891e60b57f7081ef284da2d41bc1253 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_nb/src/java/org/lamsfoundation/lams/tool/noticeboard/service/NoticeboardService.java (.../NoticeboardService.java) (revision 02b9b123b891e60b57f7081ef284da2d41bc1253) +++ lams_tool_nb/src/java/org/lamsfoundation/lams/tool/noticeboard/service/NoticeboardService.java (.../NoticeboardService.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -21,7 +21,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.tool.noticeboard.service; import java.util.ArrayList; @@ -32,8 +31,6 @@ import java.util.TreeMap; import org.apache.log4j.Logger; -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.contentrepository.exception.ItemNotFoundException; @@ -66,6 +63,8 @@ import org.lamsfoundation.lams.usermanagement.User; import org.lamsfoundation.lams.util.JsonUtil; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * An implementation of the NoticeboardService interface. * @@ -274,10 +273,10 @@ public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } - + @Override public void auditLogStartEditingActivityInMonitor(long toolContentID) { - toolService.auditLogStartEditingActivityInMonitor(toolContentID); + toolService.auditLogStartEditingActivityInMonitor(toolContentID); } @Override @@ -532,12 +531,12 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return null; } - + @Override public List getToolOutputs(String name, Long toolContentId) { return new ArrayList(); } - + @Override public List getConfidenceLevels(Long toolSessionId) { return null; @@ -630,22 +629,23 @@ return new ToolCompletionStatus( NoticeboardUser.COMPLETED.equals(learner.getUserStatus()) ? ToolCompletionStatus.ACTIVITY_COMPLETED - : ToolCompletionStatus.ACTIVITY_ATTEMPTED, null, null); + : ToolCompletionStatus.ACTIVITY_ATTEMPTED, + null, null); } // ****************** REST methods ************************* @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) { Date updateDate = new Date(); NoticeboardContent noticeboard = new NoticeboardContent(); noticeboard.setNbContentId(toolContentID); - noticeboard.setTitle(toolContentJSON.getString(RestTags.TITLE)); - noticeboard.setContent(toolContentJSON.getString("content")); - noticeboard.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - noticeboard.setReflectInstructions((String) JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, null)); + noticeboard.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE)); + noticeboard.setContent(JsonUtil.optString(toolContentJSON, "content")); + noticeboard.setReflectOnActivity( + JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); + noticeboard.setReflectInstructions(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS)); noticeboard.setCreatorUserId(userID.longValue()); noticeboard.setDateCreated(updateDate); Index: lams_tool_notebook/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_notebook/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_notebook/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -4,7 +4,7 @@ - + @@ -15,11 +15,13 @@ - + + + Index: lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/service/NotebookService.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/service/NotebookService.java (.../NotebookService.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_tool_notebook/src/java/org/lamsfoundation/lams/tool/notebook/service/NotebookService.java (.../NotebookService.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -21,7 +21,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.tool.notebook.service; import java.util.ArrayList; @@ -33,8 +32,6 @@ import java.util.SortedMap; import org.apache.log4j.Logger; -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.events.IEventNotificationService; @@ -72,6 +69,8 @@ import org.lamsfoundation.lams.util.JsonUtil; import org.lamsfoundation.lams.util.MessageService; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * An implementation of the INotebookService interface. * @@ -162,12 +161,12 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return getNotebookOutputFactory().getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public List getToolOutputs(String name, Long toolContentId) { - return new ArrayList(); + return new ArrayList<>(); } - + @Override public List getConfidenceLevels(Long toolSessionId) { return null; @@ -633,10 +632,10 @@ public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } - + @Override public void auditLogStartEditingActivityInMonitor(long toolContentID) { - toolService.auditLogStartEditingActivityInMonitor(toolContentID); + toolService.auditLogStartEditingActivityInMonitor(toolContentID); } @Override @@ -648,7 +647,7 @@ public Class[] getSupportedToolOutputDefinitionClasses(int definitionType) { return getNotebookOutputFactory().getSupportedDefinitionClasses(definitionType); } - + @Override public ToolCompletionStatus getCompletionStatus(Long learnerId, Long toolSessionId) { // db doesn't have a start/finish date for learner, and session start/finish is null @@ -667,20 +666,19 @@ * Rest call to create a new Notebook content. Required fields in toolContentJSON: "title", "instructions". */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) { Date updateDate = new Date(); Notebook nb = new Notebook(); nb.setToolContentId(toolContentID); - nb.setTitle(toolContentJSON.getString(RestTags.TITLE)); - nb.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); + nb.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE)); + nb.setInstructions(JsonUtil.optString(toolContentJSON, RestTags.INSTRUCTIONS)); nb.setCreateBy(userID.longValue()); nb.setCreateDate(updateDate); nb.setUpdateDate(updateDate); - nb.setLockOnFinished(JsonUtil.opt(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); - nb.setAllowRichEditor(JsonUtil.opt(toolContentJSON, RestTags.ALLOW_RICH_TEXT_EDITOR, Boolean.FALSE)); + nb.setLockOnFinished(JsonUtil.optBoolean(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); + nb.setAllowRichEditor(JsonUtil.optBoolean(toolContentJSON, RestTags.ALLOW_RICH_TEXT_EDITOR, Boolean.FALSE)); // submissionDeadline is set in monitoring nb.setContentInUse(false); Index: lams_tool_pixlr/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_pixlr/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_pixlr/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -4,7 +4,7 @@ - + @@ -16,7 +16,7 @@ - + Index: lams_tool_preview/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_preview/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_preview/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -10,17 +10,19 @@ - + - + - + + + Index: lams_tool_preview/src/java/org/lamsfoundation/lams/tool/peerreview/service/PeerreviewServiceImpl.java =================================================================== diff -u -re2ab99460f405e52267d81c35ddb19b37edff7f3 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_preview/src/java/org/lamsfoundation/lams/tool/peerreview/service/PeerreviewServiceImpl.java (.../PeerreviewServiceImpl.java) (revision e2ab99460f405e52267d81c35ddb19b37edff7f3) +++ lams_tool_preview/src/java/org/lamsfoundation/lams/tool/peerreview/service/PeerreviewServiceImpl.java (.../PeerreviewServiceImpl.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -41,9 +41,6 @@ import javax.servlet.http.HttpServletRequest; 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.confidencelevel.ConfidenceLevelDTO; import org.lamsfoundation.lams.contentrepository.client.IToolContentHandler; import org.lamsfoundation.lams.events.IEventNotificationService; @@ -88,6 +85,9 @@ import org.lamsfoundation.lams.util.MessageService; import org.springframework.web.util.HtmlUtils; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * @author Andrey Balan */ @@ -221,7 +221,7 @@ @Override public List getGroupSummaries(Long contentId) { - List groupList = new ArrayList(); + List groupList = new ArrayList<>(); // get all sessions in a peerreview and retrieve all peerreview items under this session // plus initial peerreview items by author creating (resItemList) @@ -366,9 +366,9 @@ } @Override - public JSONArray getUsersRatingsCommentsByCriteriaIdJSON(Long toolContentId, Long toolSessionId, + public ArrayNode getUsersRatingsCommentsByCriteriaIdJSON(Long toolContentId, Long toolSessionId, RatingCriteria criteria, Long currentUserId, Integer page, Integer size, int sorting, String searchString, - boolean getAllUsers, boolean getByUser, boolean needRatesPerUser) throws JSONException { + boolean getAllUsers, boolean getByUser, boolean needRatesPerUser) { List rawData = peerreviewUserDao.getRatingsComments(toolContentId, toolSessionId, criteria, currentUserId, page, size, sorting, searchString, getByUser, ratingService, userManagementService); @@ -514,7 +514,7 @@ public int[] getNumberPossibleRatings(Long toolContentId, Long toolSessionId, Long userId) { int[] retValue = new int[2]; - ArrayList itemIds = new ArrayList(1); + ArrayList itemIds = new ArrayList<>(1); itemIds.add(userId); Map numRatingsForUserMap = ratingService.countUsersRatedEachItem(toolContentId, toolSessionId, itemIds, -1); @@ -638,7 +638,7 @@ @Override public SortedMap getToolOutputDefinitions(Long toolContentId, int definitionType) throws ToolException { - return new TreeMap(); + return new TreeMap<>(); } @Override @@ -866,7 +866,7 @@ @Override public SortedMap getToolOutput(List names, Long toolSessionId, Long learnerId) { - return new TreeMap(); + return new TreeMap<>(); } @Override @@ -876,7 +876,7 @@ @Override public List getToolOutputs(String name, Long toolContentId) { - return new ArrayList(); + return new ArrayList<>(); } @Override @@ -959,64 +959,65 @@ /** * Used by the Rest calls to create content. Mandatory fields in toolContentJSON: title, instructions, peerreview, * user fields firstName, lastName and loginName Peerreview must contain a JSONArray of JSONObject objects, which - * have the following mandatory fields: title, description, type. It will create + * have the following mandatory fields: title, description, type. It will create */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) { Date updateDate = new Date(); Peerreview peerreview = new Peerreview(); peerreview.setContentId(toolContentID); - peerreview.setTitle(toolContentJSON.getString(RestTags.TITLE)); - peerreview.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); + peerreview.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE)); + peerreview.setInstructions(JsonUtil.optString(toolContentJSON, RestTags.INSTRUCTIONS)); peerreview.setCreated(updateDate); peerreview.setUpdated(updateDate); - peerreview.setLockWhenFinished(JsonUtil.opt(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); - peerreview.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - peerreview.setReflectInstructions(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, (String) null)); + peerreview + .setLockWhenFinished(JsonUtil.optBoolean(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); + peerreview.setReflectOnActivity( + JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); + peerreview.setReflectInstructions(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS)); peerreview.setContentInUse(false); peerreview.setDefineLater(false); PeerreviewUser peerreviewUser = getUserByIDAndContent(userID.longValue(), toolContentID); if (peerreviewUser == null) { peerreviewUser = new PeerreviewUser(); - peerreviewUser.setFirstName(toolContentJSON.getString("firstName")); - peerreviewUser.setLastName(toolContentJSON.getString("lastName")); - peerreviewUser.setLoginName(toolContentJSON.getString("loginName")); + peerreviewUser.setFirstName(JsonUtil.optString(toolContentJSON, "firstName")); + peerreviewUser.setLastName(JsonUtil.optString(toolContentJSON, "lastName")); + peerreviewUser.setLoginName(JsonUtil.optString(toolContentJSON, "loginName")); // peerreviewUser.setPeerreview(content); } peerreview.setCreatedBy(peerreviewUser); // not expecting to get these but add them in case an Authoring Template does want them - peerreview.setMinimumRates(JsonUtil.opt(toolContentJSON, "minimumRates", 0)); - peerreview.setMaximumRates(JsonUtil.opt(toolContentJSON, "maximumRate", 0)); - peerreview.setMaximumRatesPerUser(JsonUtil.opt(toolContentJSON, "maximumRatesPerUser", 0)); - peerreview.setShowRatingsLeftForUser(JsonUtil.opt(toolContentJSON, "showRatingsLeftForUser", Boolean.TRUE)); - peerreview.setShowRatingsLeftByUser(JsonUtil.opt(toolContentJSON, "showRatingsLeftByUser", Boolean.FALSE)); - peerreview.setSelfReview(JsonUtil.opt(toolContentJSON, "notifyUsersOfResults", Boolean.FALSE)); - peerreview.setNotifyUsersOfResults(JsonUtil.opt(toolContentJSON, "notifyUsersOfResults", Boolean.TRUE)); + peerreview.setMinimumRates(JsonUtil.optInt(toolContentJSON, "minimumRates", 0)); + peerreview.setMaximumRates(JsonUtil.optInt(toolContentJSON, "maximumRate", 0)); + peerreview.setMaximumRatesPerUser(JsonUtil.optInt(toolContentJSON, "maximumRatesPerUser", 0)); + peerreview.setShowRatingsLeftForUser( + JsonUtil.optBoolean(toolContentJSON, "showRatingsLeftForUser", Boolean.TRUE)); + peerreview + .setShowRatingsLeftByUser(JsonUtil.optBoolean(toolContentJSON, "showRatingsLeftByUser", Boolean.FALSE)); + peerreview.setSelfReview(JsonUtil.optBoolean(toolContentJSON, "notifyUsersOfResults", Boolean.FALSE)); + peerreview.setNotifyUsersOfResults(JsonUtil.optBoolean(toolContentJSON, "notifyUsersOfResults", Boolean.TRUE)); saveOrUpdatePeerreview(peerreview); // Criterias - JSONArray criterias = toolContentJSON.getJSONArray("criterias"); - for (int i = 0; i < criterias.length(); i++) { - JSONObject criteriaData = (JSONObject) criterias.get(i); + ArrayNode criterias = JsonUtil.optArray(toolContentJSON, "criterias"); + for (int i = 0; i < criterias.size(); i++) { + ObjectNode criteriaData = (ObjectNode) criterias.get(i); // allowComment true, minWords defaults to 1. allowComment is false, minWords defaults to 0 - boolean allowComment = criteriaData.has("commentsEnabled") ? criteriaData.getBoolean("commentsEnabled") - : false; - int minWords = criteriaData.has("minWordsInComment") ? criteriaData.getInt("minWordsInComment") - : allowComment ? 1 : 0; - ratingService.saveLearnerItemRatingCriteria(toolContentID, criteriaData.getString("title"), - criteriaData.getInt("orderId"), criteriaData.getInt("ratingStyle"), allowComment, minWords); + boolean allowComment = JsonUtil.optBoolean(criteriaData, "commentsEnabled", false); + int minWords = JsonUtil.optInt(criteriaData, "minWordsInComment", allowComment ? 1 : 0); + ratingService.saveLearnerItemRatingCriteria(toolContentID, JsonUtil.optString(criteriaData, "title"), + JsonUtil.optInt(criteriaData, "orderId"), JsonUtil.optInt(criteriaData, "ratingStyle"), + allowComment, minWords); } saveOrUpdatePeerreview(peerreview); } - } Index: lams_tool_preview/src/java/org/lamsfoundation/lams/tool/peerreview/web/action/LearningAction.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_preview/src/java/org/lamsfoundation/lams/tool/peerreview/web/action/LearningAction.java (.../LearningAction.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_tool_preview/src/java/org/lamsfoundation/lams/tool/peerreview/web/action/LearningAction.java (.../LearningAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -42,8 +42,9 @@ 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.learningdesign.dto.ActivityPositionDTO; import org.lamsfoundation.lams.notebook.model.NotebookEntry; import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; @@ -64,6 +65,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 Steve.Ni */ @@ -73,7 +77,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(); // -----------------------Peerreview Learner function --------------------------- @@ -462,7 +466,7 @@ * LearnerAction like Ranking and Hedging. */ public ActionForward getUsers(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse res) throws IOException, ServletException, JSONException { + HttpServletResponse res) throws IOException, ServletException { IPeerreviewService service = getPeerreviewService(); @@ -492,9 +496,9 @@ Long criteriaId = WebUtil.readLongParam(request, "criteriaId"); RatingCriteria criteria = service.getCriteriaByCriteriaId(criteriaId); - JSONObject responsedata = new JSONObject(); + ObjectNode responsedata = JsonNodeFactory.instance.objectNode(); responsedata.put("total_rows", service.getCountUsersBySession(toolSessionId, peerreview.isSelfReview() ? -1 : userId)); - responsedata.put("rows", service.getUsersRatingsCommentsByCriteriaIdJSON(toolContentId, toolSessionId, criteria, userId, + responsedata.set("rows", service.getUsersRatingsCommentsByCriteriaIdJSON(toolContentId, toolSessionId, criteria, userId, page, size, sorting, null, peerreview.isSelfReview(), true, peerreview.getMaximumRatesPerUser() > 0 )); responsedata.put("countRatedItems", service.getCountItemsRatedByUserByCriteria(criteriaId, userId.intValue())); @@ -625,12 +629,12 @@ * */ public ActionForward submitComments(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException, JSONException { + HttpServletResponse response) throws IOException, ServletException { return submitComments(mapping, form, request, response, false); } private ActionForward submitComments(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response, boolean ajaxResponse) throws IOException, ServletException, JSONException { + HttpServletResponse response, boolean ajaxResponse) throws IOException, ServletException { IPeerreviewService service = getPeerreviewService(); @@ -669,7 +673,7 @@ } if ( ajaxResponse ) { - JSONObject responsedata = new JSONObject(); + ObjectNode responsedata = JsonNodeFactory.instance.objectNode(); int countRatedQuestions = service.getCountItemsRatedByUserByCriteria(criteriaId, user.getUserId().intValue()); responsedata.put(AttributeNames.ATTR_COUNT_RATED_ITEMS, countRatedQuestions); responsedata.put("countCommentsSaved", countCommentsSaved); @@ -704,7 +708,7 @@ } public ActionForward submitCommentsAjax(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException, JSONException { + HttpServletResponse response) throws IOException, ServletException { return submitComments( mapping, form, request, response, true); } Index: lams_tool_sbmt/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_sbmt/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_sbmt/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -3,7 +3,7 @@ - + @@ -14,14 +14,16 @@ - - + + - - + + + + Index: lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/service/SubmitFilesService.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/service/SubmitFilesService.java (.../SubmitFilesService.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_tool_sbmt/src/java/org/lamsfoundation/lams/tool/sbmt/service/SubmitFilesService.java (.../SubmitFilesService.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -42,8 +42,6 @@ import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.struts.upload.FormFile; -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.NodeKey; import org.lamsfoundation.lams.contentrepository.client.IToolContentHandler; @@ -90,10 +88,10 @@ import org.lamsfoundation.lams.usermanagement.util.LastNameAlphabeticComparator; import org.lamsfoundation.lams.util.JsonUtil; import org.lamsfoundation.lams.util.MessageService; -import org.lamsfoundation.lams.web.session.SessionManager; -import org.lamsfoundation.lams.web.util.AttributeNames; import org.springframework.dao.DataAccessException; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * @author Manpreet Minhas */ @@ -228,13 +226,15 @@ List submissions = submissionDetailsDAO.getBySessionAndLearner(session.getSessionID(), userId); submissionDetailsDAO.deleteAll(submissions); + SubmitUser user = submitUserDAO.getLearner(session.getSessionID(), userId); if (user != null) { NotebookEntry entry = getEntry(session.getSessionID(), CoreNotebookConstants.NOTEBOOK_TOOL, SbmtConstants.TOOL_SIGNATURE, userId); if (entry != null) { submitFilesContentDAO.delete(entry); } + toolService.removeActivityMark(user.getUserID(), session.getSessionID()); submitUserDAO.delete(user); @@ -244,6 +244,7 @@ @Override public void copyLearnerContent(SubmitUser fromUser, SubmitUser toUser) throws ToolException { + if ((fromUser == null) || (toUser == null) || fromUser.getUid().equals(toUser.getUid())) { return; } @@ -425,8 +426,8 @@ "Fail to create a submission session" + " based on null toolSessionId or toolContentId"); } - log.debug("Start to create submission session based on toolSessionId[" - + toolSessionId.longValue() + "] and toolContentId[" + toolContentId.longValue() + "]"); + log.debug("Start to create submission session based on toolSessionId[" + toolSessionId.longValue() + + "] and toolContentId[" + toolContentId.longValue() + "]"); try { SubmitFilesContent submitContent = getSubmitFilesContent(toolContentId); if ((submitContent == null) || !toolContentId.equals(submitContent.getContentID())) { @@ -464,8 +465,8 @@ session.setStatus(new Integer(SubmitFilesSession.COMPLETED)); submitFilesSessionDAO.update(session); } else { - log.error("Fail to leave tool Session.Could not find submit file " - + "session by given session id: " + toolSessionId); + log.error("Fail to leave tool Session.Could not find submit file " + "session by given session id: " + + toolSessionId); throw new DataMissingException("Fail to leave tool Session." + "Could not find submit file session by given session id: " + toolSessionId); } @@ -527,7 +528,7 @@ @Override public List getToolOutputs(String name, Long toolContentId) { - return new ArrayList(); + return new ArrayList<>(); } @Override @@ -573,6 +574,7 @@ detailSet.add(details); session.setSubmissionDetails(detailSet); submissionDetailsDAO.saveOrUpdate(session); + } /** @@ -626,7 +628,6 @@ return new ArrayList(details); } - @Override public SubmissionDetails getSubmissionDetail(Long detailId) { return submissionDetailsDAO.getSubmissionDetailsByID(detailId); @@ -656,7 +657,7 @@ SubmitUserDTO submitUserDTO = new SubmitUserDTO(learner); FileDetailsDTO detailDto = new FileDetailsDTO(submissionDetails, numberFormat); - userFileList = (List) map.get(submitUserDTO); + userFileList = map.get(submitUserDTO); // if it is first time to this user, creating a new ArrayList for this user. if (userFileList == null) { userFileList = new ArrayList(); @@ -705,7 +706,7 @@ report.setMarks(marks); // If there is a new file, delete the existing and add the mark file - if ( nodeKey != null) { + if (nodeKey != null) { // Delete the existing if (report.getMarkFileUUID() != null) { @@ -722,6 +723,7 @@ submitFilesReportDAO.update(report); } + } } else { @@ -758,10 +760,10 @@ // push outputs to gradebook recalculateUserTotalMarks(isUseSelectLeaderToolOuput, session, reportID); } - + /** * Calculate user's total mark and push it to gradebook. - * + * * @param updateMarksForAllSessionUsers * whether we should update marks for all users in a session * @param session @@ -815,7 +817,7 @@ userIdToTotalMarkMap.put(userId, userTotalMark); } - + // push outputs to gradebook for (Integer userId : userIdToTotalMarkMap.keySet()) { Double userTotalMark = userIdToTotalMarkMap.get(userId) == null ? null @@ -825,11 +827,13 @@ } @Override - public void removeMarkFile(Long reportID, Long markFileUUID, Long markFileVersionID, Long sessionID) throws InvalidParameterException, RepositoryCheckedException { + public void removeMarkFile(Long reportID, Long markFileUUID, Long markFileVersionID, Long sessionID) + throws InvalidParameterException, RepositoryCheckedException { + SubmitFilesSession session = getSessionById(sessionID); SubmitFilesContent content = session.getContent(); boolean isUseSelectLeaderToolOuput = content.isUseSelectLeaderToolOuput(); - + if (isUseSelectLeaderToolOuput) { List reportIDs = submitUserDAO.getReportsForGroup(sessionID, reportID); for (Long reportIDGroup : reportIDs) { @@ -841,7 +845,7 @@ submitFilesReportDAO.update(report); } } - + } else { SubmitFilesReport report = submitFilesReportDAO.getReportByID(reportID); if (report != null) { @@ -853,6 +857,7 @@ } sbmtToolContentHandler.deleteFile(markFileUUID); + } @Override @@ -868,7 +873,7 @@ detail.setRemoved(true); submissionDetailsDAO.update(detail); - + if (detail.getReport() != null) { // push outputs to gradebook recalculateUserTotalMarks(false, detail.getSubmitFileSession(), detail.getReport().getReportID()); @@ -887,7 +892,7 @@ detail.setRemoved(false); submissionDetailsDAO.update(detail); - + if (detail.getReport() != null) { // push outputs to gradebook recalculateUserTotalMarks(false, detail.getSubmitFileSession(), detail.getReport().getReportID()); @@ -922,20 +927,20 @@ public void releaseMarksForSession(Long sessionID) { SubmitFilesSession session = getSessionById(sessionID); SubmitFilesContent content = session.getContent(); - + //set marks released indicator session.setMarksReleased(true); submitFilesSessionDAO.update(session); // push outputs to gradebook recalculateUserTotalMarks(true, session, null); - + // notify learners on mark release boolean notifyLearnersOnMarkRelease = getEventNotificationService().eventExists(SbmtConstants.TOOL_SIGNATURE, SbmtConstants.EVENT_NAME_NOTIFY_LEARNERS_ON_MARK_RELEASE, content.getContentID()); if (notifyLearnersOnMarkRelease) { Map notificationMessages = new TreeMap(); - + List list = submissionDetailsDAO.getSubmissionDetailsBySession(sessionID); for (SubmissionDetails details : list) { SubmitFilesReport report = details.getReport(); @@ -963,10 +968,11 @@ notificationMessageParameters); } } - + //audit log event - String sessionName = session.getSessionName() + " (toolSessionId=" + session.getSessionID() + ")"; - String message = messageService.getMessage("tool.display.name") + ". " + messageService.getMessage("msg.mark.released", new String[] { sessionName }); + String sessionName = session.getSessionName() + " (toolSessionId=" + session.getSessionID() + ")"; + String message = messageService.getMessage("tool.display.name") + ". " + + messageService.getMessage("msg.mark.released", new String[] { sessionName }); logEventService.logToolEvent(LogEvent.TYPE_TOOL_MARK_RELEASED, content.getContentID(), null, message); } @@ -1114,6 +1120,7 @@ submitUserDAO.saveOrUpdateUser(author); return author; + } @Override @@ -1132,6 +1139,7 @@ submitUserDAO.saveOrUpdateUser(learner); return learner; + } @Override @@ -1260,17 +1268,20 @@ for (SubmissionDetails detail : list) { Date newDate = detail.getDateOfSubmission(); 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.isFinished()) + if (learner.isFinished()) { return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_COMPLETED, startDate, endDate); - else + } else { return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_ATTEMPTED, startDate, null); + } } // ****************** REST methods ************************* @@ -1279,36 +1290,37 @@ * Used by the Rest calls to create content. Mandatory fields in toolContentJSON: title, instructions */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) { SubmitFilesContent content = new SubmitFilesContent(); Date updateDate = new Date(); content.setCreated(updateDate); content.setUpdated(updateDate); content.setContentID(toolContentID); - content.setTitle(toolContentJSON.getString(RestTags.TITLE)); - content.setInstruction(toolContentJSON.getString(RestTags.INSTRUCTIONS)); + content.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE)); + content.setInstruction(JsonUtil.optString(toolContentJSON, RestTags.INSTRUCTIONS)); content.setContentInUse(false); content.setDefineLater(false); content.setNotifyTeachersOnFileSubmit( - JsonUtil.opt(toolContentJSON, "notifyTeachersOnFileSubmit", Boolean.FALSE)); + JsonUtil.optBoolean(toolContentJSON, "notifyTeachersOnFileSubmit", Boolean.FALSE)); content.setNotifyLearnersOnMarkRelease( - JsonUtil.opt(toolContentJSON, "notifyLearnersOnMarkRelease", Boolean.FALSE)); - content.setReflectInstructions((String) JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, null)); - content.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - content.setLockOnFinished(JsonUtil.opt(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); - content.setLimitUpload(JsonUtil.opt(toolContentJSON, "limitUpload", Boolean.FALSE)); - content.setUseSelectLeaderToolOuput(JsonUtil.opt(toolContentJSON, "useSelectLeaderToolOuput", Boolean.FALSE)); - content.setLimitUploadNumber(JsonUtil.opt(toolContentJSON, "limitUploadNumber", 0)); + JsonUtil.optBoolean(toolContentJSON, "notifyLearnersOnMarkRelease", Boolean.FALSE)); + content.setReflectInstructions(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS)); + content.setReflectOnActivity(JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); + content.setLockOnFinished(JsonUtil.optBoolean(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); + content.setLimitUpload(JsonUtil.optBoolean(toolContentJSON, "limitUpload", Boolean.FALSE)); + content.setUseSelectLeaderToolOuput( + JsonUtil.optBoolean(toolContentJSON, "useSelectLeaderToolOuput", Boolean.FALSE)); + content.setLimitUploadNumber(JsonUtil.optInt(toolContentJSON, "limitUploadNumber", 0)); // submissionDeadline is set in monitoring SubmitUser user = getContentUser(toolContentID, userID); if (user == null) { - user = createContentUser(userID, toolContentJSON.getString("firstName"), - toolContentJSON.getString("lastName"), toolContentJSON.getString("loginName"), toolContentID); + user = createContentUser(userID, JsonUtil.optString(toolContentJSON, "firstName"), + JsonUtil.optString(toolContentJSON, "lastName"), JsonUtil.optString(toolContentJSON, "loginName"), + toolContentID); } content.setCreatedBy(user); saveOrUpdateContent(content); @@ -1329,7 +1341,7 @@ if (leader == null) { Long leaderUserId = toolService.getLeaderUserId(toolSessionId, user.getUserID().intValue()); if (leaderUserId != null) { - leader = submitUserDAO.getLearner(toolSessionId, (Integer) leaderUserId.intValue()); + leader = submitUserDAO.getLearner(toolSessionId, leaderUserId.intValue()); // create new user in a DB if (leader == null) { log.debug("creating new user with userId: " + leaderUserId); Index: lams_tool_scratchie/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_scratchie/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_scratchie/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -3,22 +3,24 @@ - + - - + + - - + + + + Index: lams_tool_scratchie/src/java/org/lamsfoundation/lams/tool/scratchie/service/ScratchieServiceImpl.java =================================================================== diff -u -re2ab99460f405e52267d81c35ddb19b37edff7f3 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_scratchie/src/java/org/lamsfoundation/lams/tool/scratchie/service/ScratchieServiceImpl.java (.../ScratchieServiceImpl.java) (revision e2ab99460f405e52267d81c35ddb19b37edff7f3) +++ lams_tool_scratchie/src/java/org/lamsfoundation/lams/tool/scratchie/service/ScratchieServiceImpl.java (.../ScratchieServiceImpl.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -46,9 +46,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.contentrepository.client.IToolContentHandler; import org.lamsfoundation.lams.events.IEventNotificationService; @@ -104,6 +101,9 @@ import org.lamsfoundation.lams.util.MessageService; import org.lamsfoundation.lams.util.NumberUtil; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * @author Andrey Balan */ @@ -591,7 +591,7 @@ } @Override - public void setScratchingFinished(Long toolSessionId) throws JSONException, IOException { + public void setScratchingFinished(Long toolSessionId) throws IOException { ScratchieSession session = this.getScratchieSessionBySessionId(toolSessionId); session.setScratchingFinished(true); scratchieSessionDao.saveObject(session); @@ -813,7 +813,7 @@ } /** - * Returns number of scraches user done for the specified item. + * Returns number of scraches user done for the specified item. */ private int calculateItemAttempts(List userLogs, ScratchieItem item) { @@ -1715,7 +1715,7 @@ // if there is no group leader don't calculate numbers - there aren't any if (groupLeader != null) { - + //create a list of attempts user done for the current item List itemAttempts = new ArrayList<>(); for (ScratchieAnswerVisitLog answerLog : answerLogs) { @@ -1732,7 +1732,8 @@ // find out answers' sequential letters - A,B,C... for (ScratchieAnswerVisitLog itemAttempt : itemAttempts) { - String sequencialLetter = getSequencialLetter(item, itemAttempt.getScratchieAnswer()); + String sequencialLetter = ScratchieServiceImpl.getSequencialLetter(item, + itemAttempt.getScratchieAnswer()); answersSequence += answersSequence.isEmpty() ? sequencialLetter : ", " + sequencialLetter; } @@ -1755,7 +1756,7 @@ return groupSummaries; } - + /** * Return specified answer's sequential letter (e.g. A,B,C) among other possible answers */ @@ -2166,7 +2167,6 @@ this.exportContentService = exportContentService; } - public void setLogEventService(ILogEventService logEventService) { this.logEventService = logEventService; } @@ -2236,14 +2236,13 @@ /** * Rest call to create a new Scratchie 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). */ @SuppressWarnings("unchecked") @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) { Scratchie scratchie = new Scratchie(); Date updateDate = new Date(); @@ -2253,45 +2252,47 @@ scratchie.setDefineLater(false); scratchie.setContentId(toolContentID); - scratchie.setTitle(toolContentJSON.getString(RestTags.TITLE)); - scratchie.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); + scratchie.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE)); + scratchie.setInstructions(JsonUtil.optString(toolContentJSON, RestTags.INSTRUCTIONS)); - scratchie.setBurningQuestionsEnabled(JsonUtil.opt(toolContentJSON, "burningQuestionsEnabled", Boolean.TRUE)); - scratchie.setTimeLimit(JsonUtil.opt(toolContentJSON, "timeLimit", 0)); - scratchie.setExtraPoint(JsonUtil.opt(toolContentJSON, "extraPoint", false)); - scratchie.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - scratchie.setReflectInstructions(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, (String) null)); - scratchie.setShowScrachiesInResults(JsonUtil.opt(toolContentJSON, "showScrachiesInResults", Boolean.TRUE)); - scratchie.setConfidenceLevelsActivityUiid(JsonUtil.opt(toolContentJSON, RestTags.CONFIDENCE_LEVELS_ACTIVITY_UIID, (Integer) null)); - + scratchie.setBurningQuestionsEnabled(JsonUtil.optBoolean(toolContentJSON, "burningQuestionsEnabled", true)); + scratchie.setTimeLimit(JsonUtil.optInt(toolContentJSON, "timeLimit", 0)); + scratchie.setExtraPoint(JsonUtil.optBoolean(toolContentJSON, "extraPoint", false)); + scratchie.setReflectOnActivity( + JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); + scratchie.setReflectInstructions(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS)); + scratchie.setShowScrachiesInResults(JsonUtil.optBoolean(toolContentJSON, "showScrachiesInResults", true)); + scratchie.setConfidenceLevelsActivityUiid( + JsonUtil.optInt(toolContentJSON, RestTags.CONFIDENCE_LEVELS_ACTIVITY_UIID)); + // Scratchie Items Set newItems = new LinkedHashSet<>(); - JSONArray questions = toolContentJSON.getJSONArray(RestTags.QUESTIONS); - for (int i = 0; i < questions.length(); i++) { - JSONObject questionData = (JSONObject) questions.get(i); + ArrayNode questions = JsonUtil.optArray(toolContentJSON, RestTags.QUESTIONS); + for (int i = 0; i < questions.size(); i++) { + ObjectNode questionData = (ObjectNode) questions.get(i); ScratchieItem item = new ScratchieItem(); item.setCreateDate(updateDate); item.setCreateByAuthor(true); - item.setOrderId(questionData.getInt(RestTags.DISPLAY_ORDER)); - item.setTitle(questionData.getString(RestTags.QUESTION_TITLE)); - item.setDescription(questionData.getString(RestTags.QUESTION_TEXT)); + item.setOrderId(JsonUtil.optInt(questionData, RestTags.DISPLAY_ORDER)); + item.setTitle(JsonUtil.optString(questionData, RestTags.QUESTION_TITLE)); + item.setDescription(JsonUtil.optString(questionData, RestTags.QUESTION_TEXT)); newItems.add(item); // set options Set newAnswers = new LinkedHashSet<>(); - JSONArray answersData = questionData.getJSONArray(RestTags.ANSWERS); - for (int j = 0; j < answersData.length(); j++) { - JSONObject answerData = (JSONObject) answersData.get(j); + ArrayNode answersData = JsonUtil.optArray(questionData, RestTags.ANSWERS); + for (int j = 0; j < answersData.size(); j++) { + ObjectNode answerData = (ObjectNode) answersData.get(j); ScratchieAnswer answer = new ScratchieAnswer(); // Removes redundant new line characters from options left by CKEditor (otherwise it will break // Javascript in monitor). Copied from AuthoringAction. - String answerDescription = answerData.getString(RestTags.ANSWER_TEXT); + String answerDescription = JsonUtil.optString(answerData, RestTags.ANSWER_TEXT); answer.setDescription(answerDescription != null ? answerDescription.replaceAll("[\n\r\f]", "") : ""); - answer.setCorrect(answerData.getBoolean(RestTags.CORRECT)); - answer.setOrderId(answerData.getInt(RestTags.DISPLAY_ORDER)); + answer.setCorrect(JsonUtil.optBoolean(answerData, RestTags.CORRECT)); + answer.setOrderId(JsonUtil.optInt(answerData, RestTags.DISPLAY_ORDER)); answer.setScratchieItem(item); newAnswers.add(answer); } @@ -2302,7 +2303,5 @@ scratchie.setScratchieItems(newItems); saveOrUpdateScratchie(scratchie); - } - -} +} \ No newline at end of file Index: lams_tool_scratchie/src/java/org/lamsfoundation/lams/tool/scratchie/web/action/LearningAction.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_scratchie/src/java/org/lamsfoundation/lams/tool/scratchie/web/action/LearningAction.java (.../LearningAction.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_tool_scratchie/src/java/org/lamsfoundation/lams/tool/scratchie/web/action/LearningAction.java (.../LearningAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -49,8 +49,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.learningdesign.dto.ActivityPositionDTO; import org.lamsfoundation.lams.notebook.model.NotebookEntry; import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; @@ -78,6 +76,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 */ @@ -90,7 +91,7 @@ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException, JSONException, ScratchieApplicationException, SchedulerException { + throws IOException, ServletException, ScratchieApplicationException, SchedulerException { String param = mapping.getParameter(); // -----------------------Scratchie Learner function --------------------------- @@ -349,7 +350,7 @@ service.getScratchesOrder(items, toolSessionId); } - //display confidence levels + //display confidence levels if (scratchie.isConfidenceLevelsEnabled()) { service.populateItemsWithConfidenceLevels((Long) sessionMap.get(ScratchieConstants.ATTR_USER_ID), toolSessionId, scratchie.getConfidenceLevelsActivityUiid(), items); @@ -392,7 +393,7 @@ * Record in DB that leader has scratched specified answer. And return whether scratchie answer is correct or not. */ private ActionForward recordItemScratched(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException, ScratchieApplicationException { + HttpServletResponse response) throws IOException, ScratchieApplicationException { initializeScratchieService(); String sessionMapID = WebUtil.readStrParam(request, ScratchieConstants.ATTR_SESSION_MAP_ID); SessionMap sessionMap = (SessionMap) request.getSession() @@ -420,10 +421,10 @@ return null; } - JSONObject JSONObject = new JSONObject(); - JSONObject.put(ScratchieConstants.ATTR_ANSWER_CORRECT, answer.isCorrect()); + ObjectNode ObjectNode = JsonNodeFactory.instance.objectNode(); + ObjectNode.put(ScratchieConstants.ATTR_ANSWER_CORRECT, answer.isCorrect()); response.setContentType("application/x-json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(ObjectNode); // create a new thread to record item scratched (in order to do this task in parallel not to slow down sending // response back) @@ -465,7 +466,7 @@ * Displays results page. When leader gets to this page, scratchingFinished column is set to true for all users. */ private ActionForward showResults(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws ScratchieApplicationException, JSONException, IOException { + HttpServletResponse response) throws ScratchieApplicationException, IOException { initializeScratchieService(); // get back SessionMap String sessionMapID = request.getParameter(ScratchieConstants.ATTR_SESSION_MAP_ID); @@ -556,8 +557,7 @@ } private ActionForward like(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) - throws JSONException, IOException, ServletException, ScratchieApplicationException { + HttpServletResponse response) throws IOException, ServletException, ScratchieApplicationException { initializeScratchieService(); String sessionMapID = WebUtil.readStrParam(request, ScratchieConstants.ATTR_SESSION_MAP_ID); @@ -576,16 +576,15 @@ boolean added = service.addLike(burningQuestionUid, sessionId); - JSONObject JSONObject = new JSONObject(); - JSONObject.put("added", added); + ObjectNode ObjectNode = JsonNodeFactory.instance.objectNode(); + ObjectNode.put("added", added); response.setContentType("application/json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(ObjectNode); return null; } private ActionForward removeLike(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) - throws JSONException, IOException, ServletException, ScratchieApplicationException { + HttpServletResponse response) throws IOException, ServletException, ScratchieApplicationException { initializeScratchieService(); String sessionMapID = WebUtil.readStrParam(request, ScratchieConstants.ATTR_SESSION_MAP_ID); @@ -604,10 +603,10 @@ service.removeLike(burningQuestionUid, sessionId); - JSONObject JSONObject = new JSONObject(); - JSONObject.put("added", true); + ObjectNode ObjectNode = JsonNodeFactory.instance.objectNode(); + ObjectNode.put("added", true); response.setContentType("application/json;charset=utf-8"); - response.getWriter().print(JSONObject); + response.getWriter().print(ObjectNode); return null; } @@ -696,7 +695,7 @@ * Display empty reflection form. */ private ActionForward newReflection(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws ScratchieApplicationException, JSONException, IOException { + HttpServletResponse response) throws ScratchieApplicationException, IOException { initializeScratchieService(); String sessionMapID = WebUtil.readStrParam(request, ScratchieConstants.ATTR_SESSION_MAP_ID); Index: lams_tool_scratchie/src/java/org/lamsfoundation/lams/tool/scratchie/web/action/TblMonitorAction.java =================================================================== diff -u -reef0b919074e388a593fb6d3e97ec35b60ffdcb5 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_scratchie/src/java/org/lamsfoundation/lams/tool/scratchie/web/action/TblMonitorAction.java (.../TblMonitorAction.java) (revision eef0b919074e388a593fb6d3e97ec35b60ffdcb5) +++ lams_tool_scratchie/src/java/org/lamsfoundation/lams/tool/scratchie/web/action/TblMonitorAction.java (.../TblMonitorAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -21,7 +21,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.tool.scratchie.web.action; import java.io.IOException; @@ -46,8 +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.JSONException; -import org.apache.tomcat.util.json.JSONObject; import org.lamsfoundation.lams.tool.scratchie.ScratchieConstants; import org.lamsfoundation.lams.tool.scratchie.dto.BurningQuestionDTO; import org.lamsfoundation.lams.tool.scratchie.dto.BurningQuestionItemDTO; @@ -69,6 +66,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; + public class TblMonitorAction extends LamsDispatchAction { private static Logger log = Logger.getLogger(TblMonitorAction.class); @@ -223,32 +223,33 @@ return null; } - + /** * Shows Teams page - * @throws JSONException + * + * @throws JSONException */ public ActionForward isBurningQuestionsEnabled(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException, JSONException { + HttpServletResponse response) throws IOException, ServletException { initializeScratchieService(); - + long toolContentId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID); Scratchie scratchie = scratchieService.getScratchieByContentId(toolContentId); - + // build JSON - JSONObject responseJSON = new JSONObject(); + ObjectNode responseJSON = JsonNodeFactory.instance.objectNode(); responseJSON.put("isBurningQuestionsEnabled", scratchie.isBurningQuestionsEnabled()); writeResponse(response, "text/json", LamsDispatchAction.ENCODING_UTF8, responseJSON.toString()); return null; - } + } /** * Shows Teams page */ public ActionForward burningQuestions(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { initializeScratchieService(); - + long toolContentId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID); Scratchie scratchie = scratchieService.getScratchieByContentId(toolContentId); @@ -284,25 +285,25 @@ return mapping.findForward("burningQuestions"); } - + /** * Shows Teams page */ public ActionForward getModalDialogForTeamsTab(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { initializeScratchieService(); - + long toolContentId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID); Long userId = WebUtil.readLongParam(request, AttributeNames.PARAM_USER_ID); - + ScratchieUser user = scratchieService.getUserByUserIDAndContentID(userId, toolContentId); Collection scratchieItems = user == null ? new LinkedList() : scratchieService.getItemsWithIndicatedScratches(user.getSession().getSessionId()); - + request.setAttribute("scratchieItems", scratchieItems); return mapping.findForward("teams"); } - + // ************************************************************************************* // Private method // ************************************************************************************* Index: lams_tool_scribe/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_scribe/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_scribe/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -4,7 +4,7 @@ - + @@ -16,8 +16,10 @@ - - + + + + Index: lams_tool_scribe/src/java/org/lamsfoundation/lams/tool/scribe/service/ScribeService.java =================================================================== diff -u -r02b9b123b891e60b57f7081ef284da2d41bc1253 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_scribe/src/java/org/lamsfoundation/lams/tool/scribe/service/ScribeService.java (.../ScribeService.java) (revision 02b9b123b891e60b57f7081ef284da2d41bc1253) +++ lams_tool_scribe/src/java/org/lamsfoundation/lams/tool/scribe/service/ScribeService.java (.../ScribeService.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -21,7 +21,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.tool.scribe.service; import java.util.ArrayList; @@ -34,9 +33,6 @@ import java.util.TreeMap; 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.confidencelevel.ConfidenceLevelDTO; import org.lamsfoundation.lams.contentrepository.client.IToolContentHandler; import org.lamsfoundation.lams.learningdesign.service.ExportToolContentException; @@ -71,6 +67,10 @@ import org.lamsfoundation.lams.usermanagement.dto.UserDTO; 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; + /** * An implementation of the IScribeService interface. * @@ -146,19 +146,19 @@ @Override public SortedMap getToolOutput(List names, Long toolSessionId, Long learnerId) { - return new TreeMap(); + return new TreeMap<>(); } @Override public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return null; } - + @Override public List getToolOutputs(String name, Long toolContentId) { - return new ArrayList(); + return new ArrayList<>(); } - + @Override public List getConfidenceLevels(Long toolSessionId) { return null; @@ -329,7 +329,7 @@ @Override public SortedMap getToolOutputDefinitions(Long toolContentId, int definitionType) throws ToolException { - return new TreeMap(); + return new TreeMap<>(); } @Override @@ -492,15 +492,15 @@ public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } - + @Override public void auditLogStartEditingActivityInMonitor(long toolContentID) { - toolService.auditLogStartEditingActivityInMonitor(toolContentID); + toolService.auditLogStartEditingActivityInMonitor(toolContentID); } @Override @SuppressWarnings("unchecked") - public void submitReport(Long toolSessionId, String userName, JSONObject requestJSON) throws JSONException { + public void submitReport(Long toolSessionId, String userName, ObjectNode requestJSON) { ScribeSession scribeSession = getSessionBySessionId(toolSessionId); ScribeUser scribe = scribeSession.getAppointedScribe(); if ((scribe == null) || !scribe.getLoginName().equals(userName)) { @@ -512,11 +512,10 @@ saveOrUpdateScribeUser(learner); } - JSONArray reportsJSON = requestJSON.getJSONArray("reports"); - for (int reportIndex = 0; reportIndex < reportsJSON.length(); reportIndex++) { - JSONObject reportJSON = reportsJSON.getJSONObject(reportIndex); - Long uid = reportJSON.getLong("uid"); - String text = reportJSON.getString("text"); + ArrayNode reportsJSON = JsonUtil.optArray(requestJSON, "reports"); + for (JsonNode reportJSON : reportsJSON) { + Long uid = JsonUtil.optLong(reportJSON, "uid"); + String text = JsonUtil.optString(reportJSON, "text"); for (ScribeReportEntry report : (Set) scribeSession.getScribeReportEntries()) { if (report.getUid().equals(uid)) { report.setEntryText(text); @@ -629,17 +628,16 @@ return new ToolCompletionStatus(learner.isFinishedActivity() ? ToolCompletionStatus.ACTIVITY_COMPLETED : ToolCompletionStatus.ACTIVITY_ATTEMPTED, null, null); } - + // ****************** REST methods ************************* /** * Used by the Rest calls to create content. Mandatory fields in toolContentJSON: "title", "instructions", - * "questions". Questions must contain a JSONArray of JSONObject objects, which have the following mandatory fields: + * "questions". Questions must contain a ArrayNode of ObjectNode objects, which have the following mandatory fields: * "displayOrder", "questionText" There must be at least one topic object in the "questions" array. */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) { Date updateDate = new Date(); @@ -652,25 +650,24 @@ scribe.setContentInUse(false); scribe.setDefineLater(false); - scribe.setTitle(toolContentJSON.getString(RestTags.TITLE)); - scribe.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); + scribe.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE)); + scribe.setInstructions(JsonUtil.optString(toolContentJSON, RestTags.INSTRUCTIONS)); - scribe.setAutoSelectScribe(JsonUtil.opt(toolContentJSON, "autoSelectScribe", Boolean.FALSE)); - scribe.setLockOnFinished(JsonUtil.opt(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); - scribe.setReflectInstructions((String) JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, null)); - scribe.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - scribe.setShowAggregatedReports(JsonUtil.opt(toolContentJSON, "showAggregatedReports", Boolean.FALSE)); + scribe.setAutoSelectScribe(JsonUtil.optBoolean(toolContentJSON, "autoSelectScribe", Boolean.FALSE)); + scribe.setLockOnFinished(JsonUtil.optBoolean(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); + scribe.setReflectInstructions(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS)); + scribe.setReflectOnActivity(JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); + scribe.setShowAggregatedReports(JsonUtil.optBoolean(toolContentJSON, "showAggregatedReports", Boolean.FALSE)); if (scribe.getScribeHeadings() == null) { scribe.setScribeHeadings(new HashSet()); } - JSONArray topics = toolContentJSON.getJSONArray(RestTags.QUESTIONS); - for (int i = 0; i < topics.length(); i++) { - JSONObject topic = topics.getJSONObject(i); + ArrayNode topics = JsonUtil.optArray(toolContentJSON, RestTags.QUESTIONS); + for (JsonNode topic : topics) { ScribeHeading heading = new ScribeHeading(); - heading.setDisplayOrder(topic.getInt(RestTags.DISPLAY_ORDER)); - heading.setHeadingText(topic.getString(RestTags.QUESTION_TEXT)); + heading.setDisplayOrder(JsonUtil.optInt(topic, RestTags.DISPLAY_ORDER)); + heading.setHeadingText(JsonUtil.optString(topic, RestTags.QUESTION_TEXT)); heading.setScribe(scribe); scribe.getScribeHeadings().add(heading); } Index: lams_tool_scribe/src/java/org/lamsfoundation/lams/tool/scribe/web/actions/LearningAction.java =================================================================== diff -u -rf4502360cd44d86d57b095aea5aef7ce663c8b61 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_scribe/src/java/org/lamsfoundation/lams/tool/scribe/web/actions/LearningAction.java (.../LearningAction.java) (revision f4502360cd44d86d57b095aea5aef7ce663c8b61) +++ lams_tool_scribe/src/java/org/lamsfoundation/lams/tool/scribe/web/actions/LearningAction.java (.../LearningAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -34,7 +34,7 @@ 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.notebook.model.NotebookEntry; import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; import org.lamsfoundation.lams.tool.ToolAccessMode; @@ -266,7 +266,7 @@ } public ActionForward forceCompleteActivity(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { LearningForm lrnForm = (LearningForm) form; ScribeUser scribeUser = scribeService.getUserByUID(lrnForm.getScribeUserUID()); ScribeSession session = scribeUser.getScribeSession(); Index: lams_tool_spreadsheet/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_spreadsheet/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_spreadsheet/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -4,7 +4,7 @@ - + @@ -15,13 +15,15 @@ - - + + - + + + Index: lams_tool_survey/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_survey/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_survey/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -4,7 +4,7 @@ - + @@ -15,13 +15,15 @@ - - + + - + + + Index: lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/service/SurveyServiceImpl.java =================================================================== diff -u -re2ab99460f405e52267d81c35ddb19b37edff7f3 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/service/SurveyServiceImpl.java (.../SurveyServiceImpl.java) (revision e2ab99460f405e52267d81c35ddb19b37edff7f3) +++ lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/service/SurveyServiceImpl.java (.../SurveyServiceImpl.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -38,9 +38,6 @@ import java.util.TreeSet; 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.confidencelevel.ConfidenceLevelDTO; import org.lamsfoundation.lams.contentrepository.client.IToolContentHandler; import org.lamsfoundation.lams.events.IEventNotificationService; @@ -86,6 +83,9 @@ import org.lamsfoundation.lams.util.JsonUtil; import org.lamsfoundation.lams.util.MessageService; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * @author Dapeng.Ni */ @@ -223,13 +223,13 @@ @Override public Map> getReflectList(Long contentId, boolean setEntry) { - Map> map = new HashMap>(); + Map> map = new HashMap<>(); List sessionList = surveySessionDao.getByContentId(contentId); for (SurveySession session : sessionList) { Long sessionId = session.getSessionId(); boolean hasRefection = session.getSurvey().isReflectOnActivity(); - Set list = new TreeSet(new ReflectDTOComparator()); + Set list = new TreeSet<>(new ReflectDTOComparator()); // get all users in this session List users = surveyUserDao.getBySessionID(sessionId); for (SurveyUser user : users) { @@ -299,17 +299,17 @@ @Override public List getQuestionAnswers(Long sessionId, Long userUid) { - List questions = new ArrayList(); + List questions = new ArrayList<>(); SurveySession session = surveySessionDao.getSessionBySessionId(sessionId); if (session != null) { Survey survey = session.getSurvey(); if (survey != null) { - questions = new ArrayList(survey.getQuestions()); + questions = new ArrayList<>(survey.getQuestions()); } } // set answer for this question acoording - List answers = new ArrayList(); + List answers = new ArrayList<>(); for (SurveyQuestion question : questions) { AnswerDTO answerDTO = new AnswerDTO(question); SurveyAnswer answer = surveyAnswerDao.getAnswer(question.getUid(), userUid); @@ -349,7 +349,7 @@ AnswerDTO answerDto = new AnswerDTO(question); // create a map to hold Option UID and the counts for that choice - Map optMap = new HashMap(); + Map optMap = new HashMap<>(); // total number of answers - used for the percentage calculations int numberAnswers = 0; @@ -404,7 +404,7 @@ @Override public SortedMap> getSummary(Long toolContentId) { - SortedMap> summary = new TreeMap>( + SortedMap> summary = new TreeMap<>( new SurveySessionComparator()); Survey survey = surveyDao.getByContentId(toolContentId); @@ -413,7 +413,7 @@ List sessionList = surveySessionDao.getByContentId(toolContentId); // iterator all sessions under this survey content, and get all questions and its answers. for (SurveySession session : sessionList) { - List responseList = new ArrayList(); + List responseList = new ArrayList<>(); for (SurveyQuestion question : questionList) { AnswerDTO response = getQuestionResponse(session.getSessionId(), question.getUid()); responseList.add(response); @@ -426,7 +426,7 @@ @Override public SortedMap getStatistic(Long contentId) { - SortedMap result = new TreeMap(new SurveySessionComparator()); + SortedMap result = new TreeMap<>(new SurveySessionComparator()); List stats = surveyUserDao.getStatisticsBySession(contentId); for (Object[] stat : stats) { @@ -449,7 +449,7 @@ SurveySession session = surveySessionDao.getSessionBySessionId(toolSessionID); List users = surveyUserDao.getBySessionID(toolSessionID); - Map> sessionToUsersMap = new HashMap>(); + Map> sessionToUsersMap = new HashMap<>(); sessionToUsersMap.put(session, users); return getExportSummary(sessionToUsersMap); @@ -465,11 +465,11 @@ private SortedMap>> getExportSummary( Map> sessionToUsersMap) { - SortedMap>> summary = new TreeMap>>( + SortedMap>> summary = new TreeMap<>( new SurveySessionComparator()); // all questions - List questions = new ArrayList(); + List questions = new ArrayList<>(); if (!sessionToUsersMap.isEmpty()) { SurveySession session = sessionToUsersMap.keySet().iterator().next(); Survey survey = session.getSurvey(); @@ -479,14 +479,14 @@ // traverse all sessions for (SurveySession session : sessionToUsersMap.keySet()) { - SortedMap> questionMap = new TreeMap>( + SortedMap> questionMap = new TreeMap<>( new QuestionsComparator()); // traverse all questions for (SurveyQuestion question : questions) { List users = sessionToUsersMap.get(session); - List answerDtos = new ArrayList(); + List answerDtos = new ArrayList<>(); // if it's for a single user - query DB for only one answer for this current user if (users.size() == 1) { @@ -543,10 +543,10 @@ public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } - + @Override public void auditLogStartEditingActivityInMonitor(long toolContentID) { - toolService.auditLogStartEditingActivityInMonitor(toolContentID); + toolService.auditLogStartEditingActivityInMonitor(toolContentID); } @Override @@ -849,12 +849,12 @@ public ToolOutput getToolOutput(String name, Long toolSessionId, Long learnerId) { return getSurveyOutputFactory().getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public List getToolOutputs(String name, Long toolContentId) { - return new ArrayList(); + return new ArrayList<>(); } - + @Override public List getConfidenceLevels(Long toolSessionId) { return null; @@ -955,7 +955,7 @@ return new ToolCompletionStatus(learner.isSessionFinished() ? ToolCompletionStatus.ACTIVITY_COMPLETED : ToolCompletionStatus.ACTIVITY_ATTEMPTED, null, null); } - + // ****************** REST methods ************************* /** @@ -965,62 +965,62 @@ * (default true), showOnePage (default true), notifyTeachersOnAnswerSumbit (default false), showOtherUsersAnswers * (default false), reflectOnActivity, reflectInstructions, submissionDeadline * - * Questions must contain a JSONArray of JSONObject objects, which have the following mandatory fields: - * questionText, type (1=one answer,2=multiple answers,3=free text entry) and answers. Answers is a JSONArray of + * Questions must contain a ArrayNode of ObjectNode objects, which have the following mandatory fields: + * questionText, type (1=one answer,2=multiple answers,3=free text entry) and answers. Answers is a ArrayNode of * strings, which are the answer text. A question may also have the optional fields: allowOtherTextEntry (default * false), required (default true) * * There should be at least one question object in the Questions array and at least one option in the Options array. */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) { Survey survey = new Survey(); Date updateDate = new Date(); survey.setCreated(updateDate); survey.setUpdated(updateDate); survey.setContentId(toolContentID); - survey.setTitle(toolContentJSON.getString(RestTags.TITLE)); - survey.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); + survey.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE)); + survey.setInstructions(JsonUtil.optString(toolContentJSON, RestTags.INSTRUCTIONS)); survey.setContentInUse(false); survey.setDefineLater(false); - survey.setLockWhenFinished(JsonUtil.opt(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.TRUE)); - survey.setReflectInstructions((String) JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, null)); - survey.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); + survey.setLockWhenFinished(JsonUtil.optBoolean(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.TRUE)); + survey.setReflectInstructions(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS)); + survey.setReflectOnActivity(JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); survey.setNotifyTeachersOnAnswerSumbit( - JsonUtil.opt(toolContentJSON, "notifyTeachersOnAnswerSumbit", Boolean.FALSE)); - survey.setShowOnePage(JsonUtil.opt(toolContentJSON, "showOnePage", Boolean.TRUE)); - survey.setShowOtherUsersAnswers(JsonUtil.opt(toolContentJSON, "showOtherUsersAnswers", Boolean.FALSE)); + JsonUtil.optBoolean(toolContentJSON, "notifyTeachersOnAnswerSumbit", Boolean.FALSE)); + survey.setShowOnePage(JsonUtil.optBoolean(toolContentJSON, "showOnePage", Boolean.TRUE)); + survey.setShowOtherUsersAnswers(JsonUtil.optBoolean(toolContentJSON, "showOtherUsersAnswers", Boolean.FALSE)); // submissionDeadline is set in monitoring - SurveyUser surveyUser = new SurveyUser(userID.longValue(), toolContentJSON.getString("firstName"), - toolContentJSON.getString("lastName"), toolContentJSON.getString("loginName"), survey); + SurveyUser surveyUser = new SurveyUser(userID.longValue(), JsonUtil.optString(toolContentJSON, "firstName"), + JsonUtil.optString(toolContentJSON, "lastName"), JsonUtil.optString(toolContentJSON, "loginName"), + survey); survey.setCreatedBy(surveyUser); // **************************** Handle Survey Questions ********************* - JSONArray questions = toolContentJSON.getJSONArray(RestTags.QUESTIONS); - for (int i = 0; i < questions.length(); i++) { - JSONObject questionData = (JSONObject) questions.get(i); + ArrayNode questions = JsonUtil.optArray(toolContentJSON, RestTags.QUESTIONS); + for (int i = 0; i < questions.size(); i++) { + ObjectNode questionData = (ObjectNode) questions.get(i); SurveyQuestion newQuestion = new SurveyQuestion(); newQuestion.setCreateBy(surveyUser); newQuestion.setCreateDate(updateDate); - newQuestion.setDescription(questionData.getString(RestTags.QUESTION_TEXT)); - newQuestion.setType((short) questionData.getInt("type")); - newQuestion.setAppendText(JsonUtil.opt(questionData, "allowOtherTextEntry", Boolean.FALSE)); - Boolean required = JsonUtil.opt(questionData, "required", Boolean.TRUE); + newQuestion.setDescription(JsonUtil.optString(questionData, RestTags.QUESTION_TEXT)); + newQuestion.setType((short) questionData.get("type").asInt()); + newQuestion.setAppendText(JsonUtil.optBoolean(questionData, "allowOtherTextEntry", Boolean.FALSE)); + Boolean required = JsonUtil.optBoolean(questionData, "required", Boolean.TRUE); newQuestion.setOptional(!required); newQuestion.setSequenceId(i + 1); // sequence number starts at 1 - Set newOptions = new HashSet(); - JSONArray options = questionData.getJSONArray(RestTags.ANSWERS); - for (int j = 0; j < options.length(); j++) { + Set newOptions = new HashSet<>(); + ArrayNode options = JsonUtil.optArray(questionData, RestTags.ANSWERS); + for (int j = 0; j < options.size(); j++) { SurveyOption newOption = new SurveyOption(); - newOption.setDescription(options.getString(j)); + newOption.setDescription(options.get(j).asText()); newOption.setSequenceId(j); // sequence number starts at 0 newOptions.add(newOption); } Index: lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/web/action/LearningAction.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/web/action/LearningAction.java (.../LearningAction.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_tool_survey/src/java/org/lamsfoundation/lams/tool/survey/web/action/LearningAction.java (.../LearningAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -21,7 +21,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.tool.survey.web.action; import java.io.IOException; @@ -50,9 +49,6 @@ import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; 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.learningdesign.dto.ActivityPositionDTO; import org.lamsfoundation.lams.notebook.model.NotebookEntry; import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; @@ -79,6 +75,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 Steve.Ni @@ -91,7 +91,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(); // -----------------------Survey Learner function --------------------------- @@ -147,7 +147,7 @@ AnswerForm answerForm = (AnswerForm) form; // initial Session Map - SessionMap sessionMap = new SessionMap(); + SessionMap sessionMap = new SessionMap<>(); String sessionMapID = sessionMap.getSessionID(); request.getSession().setAttribute(sessionMapID, sessionMap); answerForm.setSessionMapID(sessionMapID); @@ -306,7 +306,7 @@ } } // get current question index of total questions - int currIdx = new ArrayList(surveyItemMap.keySet()).indexOf(questionSeqID) + 1; + int currIdx = new ArrayList<>(surveyItemMap.keySet()).indexOf(questionSeqID) + 1; answerForm.setCurrentIdx(currIdx); // failure tolerance if (questionSeqID.equals(surveyItemMap.lastKey())) { @@ -341,7 +341,7 @@ } // get current question index of total questions - int currIdx = new ArrayList(surveyItemMap.keySet()).indexOf(questionSeqID) + 1; + int currIdx = new ArrayList<>(surveyItemMap.keySet()).indexOf(questionSeqID) + 1; answerForm.setCurrentIdx(currIdx); if (questionSeqID.equals(surveyItemMap.firstKey())) { @@ -357,29 +357,29 @@ HttpServletResponse response) { AnswerForm answerForm = (AnswerForm) form; Integer questionSeqID = answerForm.getQuestionSeqID(); - + String sessionMapID = answerForm.getSessionMapID(); SessionMap sessionMap = (SessionMap) request.getSession() .getAttribute(sessionMapID); SortedMap surveyItemMap = getQuestionList(sessionMap); Collection surveyItemList = surveyItemMap.values(); - if ( surveyItemList.size() < 2 || ( questionSeqID != null && questionSeqID > 0 ) ) { + if (surveyItemList.size() < 2 || (questionSeqID != null && questionSeqID > 0)) { answerForm.setPosition(SurveyConstants.POSITION_ONLY_ONE); } else { answerForm.setPosition(SurveyConstants.POSITION_FIRST); } - if ( questionSeqID == null || questionSeqID <= 0 ) { + if (questionSeqID == null || questionSeqID <= 0) { Boolean onePage = (Boolean) sessionMap.get(SurveyConstants.ATTR_SHOW_ON_ONE_PAGE); - if ( ! onePage && surveyItemList.size() > 0) { + if (!onePage && surveyItemList.size() > 0) { answerForm.setQuestionSeqID(surveyItemMap.firstKey()); questionSeqID = surveyItemMap.firstKey(); } } // get current question index of total questions - int currIdx = new ArrayList(surveyItemMap.keySet()).indexOf(questionSeqID) + 1; + int currIdx = new ArrayList<>(surveyItemMap.keySet()).indexOf(questionSeqID) + 1; answerForm.setCurrentIdx(currIdx); return mapping.findForward(SurveyConstants.SUCCESS); @@ -396,7 +396,7 @@ SortedMap surveyItemMap = getQuestionList(sessionMap); Long sessionId = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID); - List answerDtos = new ArrayList(); + List answerDtos = new ArrayList<>(); for (SurveyQuestion question : surveyItemMap.values()) { AnswerDTO answerDto = service.getQuestionResponse(sessionId, question.getUid()); answerDtos.add(answerDto); @@ -416,7 +416,7 @@ * Get OpenResponses. */ private ActionForward getOpenResponses(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse res) throws IOException, ServletException, JSONException { + HttpServletResponse res) throws IOException, ServletException { ISurveyService service = getSurveyService(); Long questionUid = WebUtil.readLongParam(request, "questionUid"); @@ -436,22 +436,22 @@ List responses = service.getOpenResponsesForTablesorter(sessionId, questionUid, page, size, sorting); - JSONArray rows = new JSONArray(); + ArrayNode rows = JsonNodeFactory.instance.arrayNode(); - JSONObject responcedata = new JSONObject(); + ObjectNode responcedata = JsonNodeFactory.instance.objectNode(); responcedata.put("total_rows", service.getCountResponsesBySessionAndQuestion(sessionId, questionUid)); for (String response : responses) { - //JSONArray cell=new JSONArray(); + //ArrayNode cell=JsonNodeFactory.instance.arrayNode(); //cell.put(HtmlUtils.htmlEscape(user.getFirstName()) + " " + HtmlUtils.htmlEscape(user.getLastName()) + " [" + HtmlUtils.htmlEscape(user.getLogin()) + "]"); - JSONObject responseRow = new JSONObject(); + ObjectNode responseRow = JsonNodeFactory.instance.objectNode(); responseRow.put("answer", StringEscapeUtils.escapeCsv(response)); // responseRow.put("attemptTime", response.getAttemptTime()); - 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; @@ -484,7 +484,7 @@ return mapping.getInputForward(); } - List answerList = new ArrayList(); + List answerList = new ArrayList<>(); for (AnswerDTO question : surveyItemList) { if (question.getAnswer() != null) { question.getAnswer().setUser(surveyLearner); @@ -722,7 +722,7 @@ SortedMap list = (SortedMap) sessionMap .get(SurveyConstants.ATTR_QUESTION_LIST); if (list == null) { - list = new TreeMap(new IntegerComparator()); + list = new TreeMap<>(new IntegerComparator()); sessionMap.put(SurveyConstants.ATTR_QUESTION_LIST, list); } return list; Index: lams_tool_task/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_task/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_task/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -4,9 +4,9 @@ - + - + @@ -15,13 +15,15 @@ - - + + - + + + Index: lams_tool_videorecorder/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_videorecorder/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_videorecorder/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -4,7 +4,7 @@ - + @@ -16,7 +16,7 @@ - + Index: lams_tool_vote/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_vote/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_vote/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -4,7 +4,7 @@ - + @@ -15,11 +15,13 @@ > - + + + Index: lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/service/VoteService.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/service/VoteService.java (.../VoteService.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/service/VoteService.java (.../VoteService.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -43,9 +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.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.learningdesign.DataFlowObject; @@ -104,6 +101,9 @@ import org.lamsfoundation.lams.web.util.AttributeNames; import org.springframework.dao.DataAccessException; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * The POJO implementation of Voting service. All business logic of Voting tool is implemented in this class. It * translates the request from presentation layer and performs appropriate database operation. @@ -266,7 +266,7 @@ Map mapStandardNominationsContent = new TreeMap(new VoteComparator()); Map mapVoteRates = new TreeMap(new VoteComparator()); - for (VoteQueContent question : (Set) voteContent.getVoteQueContents()) { + for (VoteQueContent question : voteContent.getVoteQueContents()) { mapStandardNominationsHTMLedContent.put(mapIndex, question.getQuestion()); String noHTMLNomination = VoteUtils.stripHTML(question.getQuestion()); @@ -322,7 +322,7 @@ LinkedList sessionDTOs = new LinkedList(); VoteContent voteContent = this.getVoteContent(toolContentID); - for (VoteSession session : (Set) voteContent.getVoteSessions()) { + for (VoteSession session : voteContent.getVoteSessions()) { SessionDTO sessionDTO = new SessionDTO(); sessionDTO.setSessionId(session.getVoteSessionId().toString()); @@ -339,7 +339,7 @@ Map mapStandardQuestionUid = new TreeMap(new VoteComparator()); Map mapStandardToolSessionUid = new TreeMap(new VoteComparator()); - for (VoteQueContent question : (Set) voteContent.getVoteQueContents()) { + for (VoteQueContent question : voteContent.getVoteQueContents()) { mapStandardNominationsHTMLedContent.put(mapIndex, question.getQuestion()); int votesCount = voteUsrAttemptDAO.getStandardAttemptsForQuestionContentAndSessionUid(question.getUid(), @@ -402,10 +402,11 @@ totalCompletedSessionUserCount += sessionDTO.getCompletedSessionUserCount(); Long mapIndex = 1L; - for (VoteQueContent question : (Set) voteContent.getVoteQueContents()) { + for (VoteQueContent question : voteContent.getVoteQueContents()) { Long votesCount = sessionDTO.getMapStandardUserCount().get(mapIndex); Long oldTotalVotesCount = (totalMapStandardUserCount.get(mapIndex) != null) - ? totalMapStandardUserCount.get(mapIndex) : 0L; + ? totalMapStandardUserCount.get(mapIndex) + : 0L; totalMapStandardUserCount.put(mapIndex, oldTotalVotesCount + votesCount); allSessionsVotesCount += votesCount; @@ -418,7 +419,8 @@ if (voteContent.isAllowText()) { Long votesCount = sessionDTO.getMapStandardUserCount().get(mapIndex); Long oldTotalVotesCount = (totalMapStandardUserCount.get(mapIndex) != null) - ? totalMapStandardUserCount.get(mapIndex) : 0L; + ? totalMapStandardUserCount.get(mapIndex) + : 0L; totalMapStandardUserCount.put(mapIndex, oldTotalVotesCount + votesCount); allSessionsVotesCount += votesCount; @@ -441,7 +443,7 @@ Long mapIndex = 1L; Map totalMapVoteRates = new TreeMap(new VoteComparator()); int totalStandardVotesCount = 0; - for (VoteQueContent question : (Set) voteContent.getVoteQueContents()) { + for (VoteQueContent question : voteContent.getVoteQueContents()) { Long votesCount = totalMapStandardUserCount.get(mapIndex); @@ -474,7 +476,7 @@ SortedSet sessionDTOs = new TreeSet(); VoteContent voteContent = this.getVoteContent(toolContentID); - for (VoteSession session : (Set) voteContent.getVoteSessions()) { + for (VoteSession session : voteContent.getVoteSessions()) { SummarySessionDTO sessionDTO = new SummarySessionDTO(); sessionDTO.setSessionName(session.getSession_name()); @@ -486,7 +488,7 @@ int totalStandardVotesCount = 0; - for (VoteQueContent question : (Set) voteContent.getVoteQueContents()) { + for (VoteQueContent question : voteContent.getVoteQueContents()) { SessionNominationDTO nominationDTO = new SessionNominationDTO(); nominationDTO.setQuestionUid(question.getUid()); @@ -1323,7 +1325,7 @@ return; } - for (VoteSession session : (Set) voteContent.getVoteSessions()) { + for (VoteSession session : voteContent.getVoteSessions()) { List entries = coreNotebookService.getEntry(session.getVoteSessionId(), CoreNotebookConstants.NOTEBOOK_TOOL, VoteAppConstants.MY_SIGNATURE); for (NotebookEntry entry : entries) { @@ -1347,7 +1349,7 @@ return; } - for (VoteSession session : (Set) voteContent.getVoteSessions()) { + for (VoteSession session : voteContent.getVoteSessions()) { VoteQueUsr user = voteUserDAO.getVoteUserBySession(userId.longValue(), session.getUid()); if (user != null) { voteUsrAttemptDAO.removeAttemptsForUserandSession(user.getUid(), session.getUid()); @@ -1559,10 +1561,10 @@ public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } - + @Override public void auditLogStartEditingActivityInMonitor(long toolContentID) { - toolService.auditLogStartEditingActivityInMonitor(toolContentID); + toolService.auditLogStartEditingActivityInMonitor(toolContentID); } @Override @@ -1589,7 +1591,7 @@ @Override public boolean isReadOnly(Long toolContentId) { VoteContent voteContent = voteContentDAO.getVoteContentByContentId(toolContentId); - for (VoteSession session : (Set) voteContent.getVoteSessions()) { + for (VoteSession session : voteContent.getVoteSessions()) { if (!session.getVoteQueUsers().isEmpty()) { return true; } @@ -1612,7 +1614,7 @@ public List getToolOutputs(String name, Long toolContentId) { return new ArrayList(); } - + @Override public List getConfidenceLevels(Long toolSessionId) { return null; @@ -1961,35 +1963,36 @@ return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_NOT_ATTEMPTED, null, null); } - Date startDate = null; Date endDate = null; Set attempts = learner.getVoteUsrAttempts(); // expect only one for (VoteUsrAttempt 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); + } } // ****************** REST methods ************************* /** * Rest call to create a new Vote content. Required fields in toolContentJSON: "title", "instructions", "answers". - * The "answers" entry should be a JSONArray of Strings. + * The "answers" entry should be a ArrayNode of Strings. */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) { if (logger.isDebugEnabled()) { logger.debug("Rest call to create a new Vote content for userID" + userID + " and toolContentID " + toolContentID); @@ -1998,39 +2001,42 @@ VoteContent vote = new VoteContent(); vote.setVoteContentId(toolContentID); - vote.setTitle(toolContentJSON.getString(RestTags.TITLE)); - vote.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); + vote.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE)); + vote.setInstructions(JsonUtil.optString(toolContentJSON, RestTags.INSTRUCTIONS)); vote.setCreatedBy(userID); vote.setCreationDate(updateDate); vote.setUpdateDate(updateDate); - vote.setAllowText(JsonUtil.opt(toolContentJSON, "allowText", Boolean.FALSE)); + vote.setAllowText(JsonUtil.optBoolean(toolContentJSON, "allowText", Boolean.FALSE)); vote.setDefineLater(false); - vote.setLockOnFinish(JsonUtil.opt(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); - vote.setMaxNominationCount(JsonUtil.opt(toolContentJSON, "maxNominations", "1")); - vote.setMinNominationCount(JsonUtil.opt(toolContentJSON, "minNominations", "1")); - vote.setReflect(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - vote.setReflectionSubject(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, (String) null)); - vote.setShowResults(JsonUtil.opt(toolContentJSON, "showResults", Boolean.TRUE)); + vote.setLockOnFinish(JsonUtil.optBoolean(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); + vote.setMaxNominationCount(JsonUtil.optString(toolContentJSON, "maxNominations", "1")); + vote.setMinNominationCount(JsonUtil.optString(toolContentJSON, "minNominations", "1")); + vote.setReflect(JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); + vote.setReflectionSubject(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS)); + vote.setShowResults(JsonUtil.optBoolean(toolContentJSON, "showResults", Boolean.TRUE)); vote.setUseSelectLeaderToolOuput( - JsonUtil.opt(toolContentJSON, RestTags.USE_SELECT_LEADER_TOOL_OUTPUT, Boolean.FALSE)); + JsonUtil.optBoolean(toolContentJSON, RestTags.USE_SELECT_LEADER_TOOL_OUTPUT, Boolean.FALSE)); // Is the data flow functionality actually used anywhere? - vote.setAssignedDataFlowObject((Boolean) JsonUtil.opt(toolContentJSON, "assignedDataFlowObject", null)); - vote.setExternalInputsAdded((Short) JsonUtil.opt(toolContentJSON, "externalInputsAdded", null)); - vote.setMaxExternalInputs(JsonUtil.opt(toolContentJSON, "maxInputs", Short.valueOf("0"))); + vote.setAssignedDataFlowObject(JsonUtil.optBoolean(toolContentJSON, "assignedDataFlowObject")); + Integer externalInputsAdded = JsonUtil.optInt(toolContentJSON, "externalInputsAdded"); + if (externalInputsAdded != null) { + vote.setExternalInputsAdded(externalInputsAdded.shortValue()); + } + vote.setMaxExternalInputs(JsonUtil.optInt(toolContentJSON, "maxInputs", 0).shortValue()); // submissionDeadline is set in monitoring // **************************** Nomination entries ********************* - JSONArray answers = toolContentJSON.getJSONArray(RestTags.ANSWERS); + ArrayNode answers = JsonUtil.optArray(toolContentJSON, RestTags.ANSWERS); //Set newAnswersSet = vote.getVoteQueContents(); - for (int i = 0; i < answers.length(); i++) { + for (int i = 0; i < answers.size(); i++) { // String answerJSONData = (String) answers.get(i); VoteQueContent answer = new VoteQueContent(); answer.setDisplayOrder(i + 1); answer.setMcContent(vote); - answer.setQuestion((String) answers.get(i)); + answer.setQuestion(answers.get(i).asText()); answer.setVoteContent(vote); vote.getVoteQueContents().add(answer); } Index: lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/action/LearningAction.java =================================================================== diff -u -r471b903caa3365758fbdec0a22440b1b0b3f2947 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/action/LearningAction.java (.../LearningAction.java) (revision 471b903caa3365758fbdec0a22440b1b0b3f2947) +++ lams_tool_vote/src/java/org/lamsfoundation/lams/tool/vote/web/action/LearningAction.java (.../LearningAction.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -45,8 +45,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.notebook.model.NotebookEntry; import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants; import org.lamsfoundation.lams.tool.ToolAccessMode; @@ -72,6 +70,9 @@ import org.lamsfoundation.lams.web.session.SessionManager; import org.lamsfoundation.lams.web.util.AttributeNames; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * @author Ozgur Demirtas */ @@ -209,7 +210,7 @@ Iterator listIterator = attempts.iterator(); int order = 0; while (listIterator.hasNext()) { - VoteUsrAttempt attempt = (VoteUsrAttempt) listIterator.next(); + VoteUsrAttempt attempt = listIterator.next(); VoteQueContent voteQueContent = attempt.getVoteQueContent(); order++; if (voteQueContent != null) { @@ -533,7 +534,7 @@ * checks Leader Progress */ public ActionForward checkLeaderProgress(ActionMapping mapping, ActionForm form, HttpServletRequest request, - HttpServletResponse response) throws JSONException, IOException { + HttpServletResponse response) throws IOException { IVoteService voteService = VoteServiceProxy.getVoteService(getServlet().getServletContext()); Long toolSessionId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID); @@ -544,10 +545,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; } @@ -836,7 +837,8 @@ // store group leader information voteLearningForm.setGroupLeaderName(groupLeader.getFullname()); - voteLearningForm.setGroupLeaderUserId(groupLeader.getQueUsrId() != null ? groupLeader.getQueUsrId().toString() : ""); + voteLearningForm.setGroupLeaderUserId( + groupLeader.getQueUsrId() != null ? groupLeader.getQueUsrId().toString() : ""); boolean isUserLeader = voteService.isUserGroupLeader(user, new Long(toolSessionID)); voteLearningForm.setIsUserLeader(isUserLeader); } @@ -928,7 +930,7 @@ Iterator listIterator = attempts.iterator(); int order = 0; while (listIterator.hasNext()) { - VoteUsrAttempt attempt = (VoteUsrAttempt) listIterator.next(); + VoteUsrAttempt attempt = listIterator.next(); VoteQueContent voteQueContent = attempt.getVoteQueContent(); order++; if (voteQueContent != null) { Index: lams_tool_wiki/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_wiki/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_wiki/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -9,8 +9,8 @@ - - + + @@ -20,6 +20,8 @@ - + + + Index: lams_tool_wiki/src/java/org/lamsfoundation/lams/tool/wiki/service/WikiService.java =================================================================== diff -u -r02b9b123b891e60b57f7081ef284da2d41bc1253 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_wiki/src/java/org/lamsfoundation/lams/tool/wiki/service/WikiService.java (.../WikiService.java) (revision 02b9b123b891e60b57f7081ef284da2d41bc1253) +++ lams_tool_wiki/src/java/org/lamsfoundation/lams/tool/wiki/service/WikiService.java (.../WikiService.java) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -21,7 +21,6 @@ * **************************************************************** */ - package org.lamsfoundation.lams.tool.wiki.service; import java.util.ArrayList; @@ -34,9 +33,6 @@ import java.util.SortedMap; 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.confidencelevel.ConfidenceLevelDTO; import org.lamsfoundation.lams.contentrepository.client.IToolContentHandler; import org.lamsfoundation.lams.events.IEventNotificationService; @@ -79,6 +75,9 @@ import org.lamsfoundation.lams.util.JsonUtil; import org.lamsfoundation.lams.util.MessageService; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + /** * An implementation of the IWikiService interface. * @@ -137,7 +136,7 @@ session.setWiki(wiki); // Create an empty list to copy the wiki pages into - Set sessionWikiPages = new HashSet(); + Set sessionWikiPages = new HashSet<>(); // Here we need to clone wikipages and content for tool session versions //for (WikiPage childPage : wiki.getWikiPages()) { // LDEV-2436 @@ -217,12 +216,12 @@ } return wikiOutputFactory.getToolOutput(name, this, toolSessionId, learnerId); } - + @Override public List getToolOutputs(String name, Long toolContentId) { - return new ArrayList(); + return new ArrayList<>(); } - + @Override public List getConfidenceLevels(Long toolSessionId) { return null; @@ -485,7 +484,7 @@ Diff diff = new Diff(oldArray, currentArray); List diffOut = diff.diff(); - LinkedList result = new LinkedList(Arrays.asList(currentArray)); + LinkedList result = new LinkedList<>(Arrays.asList(currentArray)); int resultOffset = 0; for (Difference difference : diffOut) { @@ -834,10 +833,10 @@ public boolean isGroupedActivity(long toolContentID) { return toolService.isGroupedActivity(toolContentID); } - + @Override public void auditLogStartEditingActivityInMonitor(long toolContentID) { - toolService.auditLogStartEditingActivityInMonitor(toolContentID); + toolService.auditLogStartEditingActivityInMonitor(toolContentID); } @Override @@ -1023,12 +1022,13 @@ // very complicated to try to work out from edit page, so not doing dates. - if (learner.isFinishedActivity()) + if (learner.isFinishedActivity()) { return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_COMPLETED, null, null); - else + } else { return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_ATTEMPTED, null, null); + } } - + /* ****************** REST methods **************************************************************************/ /** @@ -1039,57 +1039,59 @@ * allowLearnerCreatePages (default True), allowLearnerInsertLinks (default True) notifyUpdates (default False), * minimumEdits and maximumEdits (default 0, no min/max) * - * Pages is a JSONArray of JSONObjects, where each object represents a Wiki page. The first entry in the array + * Pages is a ArrayNode of ObjectNodes, where each object represents a Wiki page. The first entry in the array * becomes the main page. Withing the wiki page object, mandatory fields are title and body. Optional field is * readOnly, which defaults to false (ie the user can edit the page). */ @Override - public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON) - throws JSONException { + public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) { Wiki content = new Wiki(); Date updateDate = new Date(); content.setCreateDate(updateDate); content.setUpdateDate(updateDate); content.setCreateBy(userID.longValue()); content.setToolContentId(toolContentID); - content.setTitle(toolContentJSON.getString(RestTags.TITLE)); + content.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE)); // No instructions are available in the current wiki implementation // content.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS)); content.setContentInUse(false); content.setDefineLater(false); - content.setReflectInstructions((String) JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, null)); - content.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); - content.setLockOnFinished(JsonUtil.opt(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); + content.setReflectInstructions(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS)); + content.setReflectOnActivity(JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE)); + content.setLockOnFinished(JsonUtil.optBoolean(toolContentJSON, RestTags.LOCK_WHEN_FINISHED, Boolean.FALSE)); - content.setAllowLearnerAttachImages(JsonUtil.opt(toolContentJSON, "allowLearnerAttachImages", Boolean.TRUE)); - content.setAllowLearnerCreatePages(JsonUtil.opt(toolContentJSON, "allowLearnerCreatePages", Boolean.TRUE)); - content.setAllowLearnerInsertLinks(JsonUtil.opt(toolContentJSON, "allowLearnerInsertLinks", Boolean.TRUE)); - content.setNotifyUpdates(JsonUtil.opt(toolContentJSON, "notifyUpdates", Boolean.FALSE)); - content.setMinimumEdits(JsonUtil.opt(toolContentJSON, "minimumEdits", 0)); - content.setMaximumEdits(JsonUtil.opt(toolContentJSON, "maximumEdits", 0)); + content.setAllowLearnerAttachImages( + JsonUtil.optBoolean(toolContentJSON, "allowLearnerAttachImages", Boolean.TRUE)); + content.setAllowLearnerCreatePages( + JsonUtil.optBoolean(toolContentJSON, "allowLearnerCreatePages", Boolean.TRUE)); + content.setAllowLearnerInsertLinks( + JsonUtil.optBoolean(toolContentJSON, "allowLearnerInsertLinks", Boolean.TRUE)); + content.setNotifyUpdates(JsonUtil.optBoolean(toolContentJSON, "notifyUpdates", Boolean.FALSE)); + content.setMinimumEdits(JsonUtil.optInt(toolContentJSON, "minimumEdits", 0)); + content.setMaximumEdits(JsonUtil.optInt(toolContentJSON, "maximumEdits", 0)); /* ********************** Handle pages ***************************************************** */ - /* The first page becomes the main page, all other pages saved in the order in the JSONArray */ + /* The first page becomes the main page, all other pages saved in the order in the ArrayNode */ boolean firstEntry = true; content.setWikiPages(new HashSet()); - JSONArray pages = toolContentJSON.getJSONArray("pages"); - for (int i = 0; i < pages.length(); i++) { - JSONObject pageData = (JSONObject) pages.get(i); + ArrayNode pages = JsonUtil.optArray(toolContentJSON, "pages"); + for (int i = 0; i < pages.size(); i++) { + ObjectNode pageData = (ObjectNode) pages.get(i); WikiPage wikiPage = new WikiPage(); - Boolean isReadOnly = JsonUtil.opt(pageData, RestTags.READ_ONLY, Boolean.FALSE); + Boolean isReadOnly = JsonUtil.optBoolean(pageData, RestTags.READ_ONLY, Boolean.FALSE); wikiPage.setEditable(!isReadOnly); wikiPage.setParentWiki(content); - wikiPage.setTitle(pageData.getString(RestTags.TITLE)); + wikiPage.setTitle(JsonUtil.optString(pageData, RestTags.TITLE)); wikiPage.setAddedBy(null); wikiPage.setWikiContentVersions(new HashSet()); wikiPage.setWikiSession(null); // Create a new wiki page content using the wiki page form WikiPageContent wikiPageContent = new WikiPageContent(); - wikiPageContent.setBody(pageData.getString("body")); + wikiPageContent.setBody(JsonUtil.optString(pageData, "body")); wikiPageContent.setEditDate(updateDate); wikiPageContent.setEditor(null); wikiPageContent.setVersion(new Long(1)); Index: lams_tool_wookie/.classpath =================================================================== diff -u -r8236da64800893104429c9b88f89d500c505a9a1 -r344a7854d00abbb7a6bb0bb3756970234be71f76 --- lams_tool_wookie/.classpath (.../.classpath) (revision 8236da64800893104429c9b88f89d500c505a9a1) +++ lams_tool_wookie/.classpath (.../.classpath) (revision 344a7854d00abbb7a6bb0bb3756970234be71f76) @@ -4,7 +4,7 @@ - + @@ -16,7 +16,7 @@ - +