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