Index: lams_admin/src/java/org/lamsfoundation/lams/admin/web/action/OrgManageAction.java
===================================================================
diff -u
--- lams_admin/src/java/org/lamsfoundation/lams/admin/web/action/OrgManageAction.java (revision 0)
+++ lams_admin/src/java/org/lamsfoundation/lams/admin/web/action/OrgManageAction.java (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -0,0 +1,232 @@
+/****************************************************************
+ * 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.admin.web.action;
+
+import java.io.IOException;
+import java.util.List;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.lang.StringEscapeUtils;
+import org.apache.struts.action.ActionForm;
+import org.apache.struts.action.ActionForward;
+import org.apache.struts.action.ActionMapping;
+import org.lamsfoundation.lams.admin.service.AdminServiceProxy;
+import org.lamsfoundation.lams.admin.web.form.OrgManageForm;
+import org.lamsfoundation.lams.security.ISecurityService;
+import org.lamsfoundation.lams.usermanagement.Organisation;
+import org.lamsfoundation.lams.usermanagement.OrganisationState;
+import org.lamsfoundation.lams.usermanagement.OrganisationType;
+import org.lamsfoundation.lams.usermanagement.Role;
+import org.lamsfoundation.lams.usermanagement.dto.UserDTO;
+import org.lamsfoundation.lams.usermanagement.service.IUserManagementService;
+import org.lamsfoundation.lams.usermanagement.service.UserManagementService;
+import org.lamsfoundation.lams.util.MessageService;
+import org.lamsfoundation.lams.util.WebUtil;
+import org.lamsfoundation.lams.web.action.LamsDispatchAction;
+import org.lamsfoundation.lams.web.session.SessionManager;
+import org.lamsfoundation.lams.web.util.AttributeNames;
+import org.springframework.web.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;
+
+/**
+ *
+ * View Source
+ *
+ *
+ * @author Fei Yang
+ */
+public class OrgManageAction extends LamsDispatchAction {
+
+ private static IUserManagementService userManagementService;
+
+ @Override
+ public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) throws Exception {
+ initServices();
+
+ // Get organisation whose child organisations we will populate the OrgManageForm with
+ Integer orgId = WebUtil.readIntParam(request, "org", true);
+ if (orgId == null) {
+ orgId = (Integer) request.getAttribute("org");
+ }
+ if ((orgId == null) || (orgId == 0)) {
+ response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing organisation ID");
+ return null;
+ }
+
+ // get logged in user's id
+ Integer userId = ((UserDTO) SessionManager.getSession().getAttribute(AttributeNames.USER)).getUserID();
+ ISecurityService securityService = AdminServiceProxy.getSecurityService(getServlet().getServletContext());
+
+ Organisation org = null;
+ boolean isRootOrganisation = false;
+ Organisation rootOrganisation = userManagementService.getRootOrganisation();
+ if (orgId.equals(rootOrganisation.getOrganisationId())) {
+ org = rootOrganisation;
+ isRootOrganisation = true;
+ } else {
+ org = (Organisation) userManagementService.findById(Organisation.class, orgId);
+ }
+
+ // check if user is allowed to view and edit groups
+ if (!request.isUserInRole(Role.SYSADMIN) && !(isRootOrganisation
+ ? request.isUserInRole(Role.GROUP_ADMIN) || request.isUserInRole(Role.GROUP_MANAGER)
+ : securityService.hasOrgRole(orgId, userId, new String[] { Role.GROUP_ADMIN, Role.GROUP_MANAGER },
+ "manage courses", false))) {
+ response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not a manager or admin in the organisation");
+ return null;
+ }
+
+ // get number of users figure
+ // TODO use hql that does a count instead of getting whole objects
+ int numUsers = org == rootOrganisation ? userManagementService.getCountUsers()
+ : userManagementService.getUsersFromOrganisation(orgId).size();
+ String key = org == rootOrganisation ? "label.users.in.system" : "label.users.in.group";
+ MessageService messageService = AdminServiceProxy.getMessageService(getServlet().getServletContext());
+ request.setAttribute("numUsers", messageService.getMessage(key, new String[] { String.valueOf(numUsers) }));
+
+ // Set OrgManageForm
+ OrgManageForm orgManageForm = (OrgManageForm) form;
+ if (orgManageForm == null) {
+ orgManageForm = new OrgManageForm();
+ orgManageForm.setStateId(OrganisationState.ACTIVE);
+ } else if (orgManageForm.getStateId() == null) {
+ orgManageForm.setStateId(OrganisationState.ACTIVE);
+ }
+ orgManageForm.setParentId(orgId);
+ orgManageForm.setParentName(org.getName());
+ orgManageForm.setType(org.getOrganisationType().getOrganisationTypeId());
+
+ // Get list of child organisations depending on requestor's role and the organisation's type
+ if (orgManageForm.getType().equals(OrganisationType.CLASS_TYPE)) {
+ // display class info, with parent group's 'courseAdminCan...' permissions.
+ // note the org is not saved, properties set only for passing to view component.
+ Organisation pOrg = org.getParentOrganisation();
+ org.setCourseAdminCanAddNewUsers(pOrg.getCourseAdminCanAddNewUsers());
+ org.setCourseAdminCanBrowseAllUsers(pOrg.getCourseAdminCanBrowseAllUsers());
+ org.setCourseAdminCanChangeStatusOfCourse(pOrg.getCourseAdminCanChangeStatusOfCourse());
+ request.setAttribute("org", org);
+
+ // display parent org breadcrumb link
+ request.setAttribute("parentGroupName", pOrg.getName());
+ request.setAttribute("parentGroupId", pOrg.getOrganisationId());
+ } else {
+ request.setAttribute("OrgManageForm", orgManageForm);
+
+ // display org info
+ request.setAttribute("org", org);
+ }
+
+ // let the jsp know whether to display links
+ request.setAttribute("createGroup",
+ request.isUserInRole(Role.SYSADMIN) || userManagementService.isUserGlobalGroupAdmin());
+ request.setAttribute("editGroup", true);
+ request.setAttribute("manageGlobalRoles", request.isUserInRole(Role.SYSADMIN));
+ return mapping.findForward("orglist");
+ }
+
+ /**
+ * Returns list of organisations for .
+ */
+ public ActionForward getOrgs(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse res) throws IOException, ServletException {
+ initServices();
+
+ Integer parentOrgId = WebUtil.readIntParam(request, "parentOrgId");
+ Integer stateId = WebUtil.readIntParam(request, "stateId");
+ Integer typeIdParam = WebUtil.readIntParam(request, "type");
+ // the organisation type of the children
+ Integer typeId = (typeIdParam.equals(OrganisationType.ROOT_TYPE) ? OrganisationType.COURSE_TYPE
+ : OrganisationType.CLASS_TYPE);
+ String searchString = WebUtil.readStrParam(request, "fcol[1]", true);
+
+ // paging parameters of tablesorter
+ int size = WebUtil.readIntParam(request, "size");
+ int page = WebUtil.readIntParam(request, "page");
+ Integer isSort1 = WebUtil.readIntParam(request, "column[0]", true);
+ Integer isSort2 = WebUtil.readIntParam(request, "column[1]", true);
+ Integer isSort3 = WebUtil.readIntParam(request, "column[2]", true);
+ Integer isSort4 = WebUtil.readIntParam(request, "column[3]", true);
+
+ String sortBy = "";
+ String sortOrder = "";
+ if (isSort1 != null) {
+ sortBy = "id";
+ sortOrder = isSort1.equals(0) ? "ASC" : "DESC";
+
+ } else if (isSort2 != null) {
+ sortBy = "name";
+ sortOrder = isSort2.equals(0) ? "ASC" : "DESC";
+
+ } else if (isSort3 != null) {
+ sortBy = "code";
+ sortOrder = isSort3.equals(0) ? "ASC" : "DESC";
+
+ } else if (isSort4 != null) {
+ sortBy = "description";
+ sortOrder = isSort4.equals(0) ? "ASC" : "DESC";
+
+ }
+
+ List organisations = userManagementService.getPagedCourses(parentOrgId, typeId, stateId, page,
+ size, sortBy, sortOrder, searchString);
+
+ ObjectNode responseJSON = JsonNodeFactory.instance.objectNode();
+ responseJSON.put("total_rows", userManagementService.getCountCoursesByParentCourseAndTypeAndState(parentOrgId,
+ typeId, stateId, searchString));
+
+ ArrayNode rows = JsonNodeFactory.instance.arrayNode();
+ for (Organisation organisation : organisations) {
+ ObjectNode responseRow = JsonNodeFactory.instance.objectNode();
+ responseRow.put("id", organisation.getOrganisationId());
+ String orgName = organisation.getName() == null ? "" : organisation.getName();
+ responseRow.put("name", StringEscapeUtils.escapeHtml(orgName));
+ String orgCode = organisation.getCode() == null ? "" : organisation.getCode();
+ responseRow.put("code", StringEscapeUtils.escapeHtml(orgCode));
+ String orgDescription = organisation.getDescription() == null ? "" : organisation.getDescription();
+ responseRow.put("description", StringEscapeUtils.escapeHtml(orgDescription));
+
+ rows.add(responseRow);
+ }
+
+ responseJSON.set("rows", rows);
+ res.setContentType("application/json;charset=utf-8");
+ res.getWriter().print(responseJSON.toString());
+ return null;
+ }
+
+ private void initServices() {
+ if (userManagementService == null) {
+ WebApplicationContext ctx = WebApplicationContextUtils
+ .getWebApplicationContext(getServlet().getServletContext());
+ userManagementService = (UserManagementService) ctx.getBean("userManagementService");
+ }
+ }
+}
\ No newline at end of file
Index: lams_admin/src/java/org/lamsfoundation/lams/admin/web/action/ToolContentListAction.java
===================================================================
diff -u
--- lams_admin/src/java/org/lamsfoundation/lams/admin/web/action/ToolContentListAction.java (revision 0)
+++ lams_admin/src/java/org/lamsfoundation/lams/admin/web/action/ToolContentListAction.java (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -0,0 +1,328 @@
+/****************************************************************
+ * 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.admin.web.action;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import javax.sql.DataSource;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.struts.action.Action;
+import org.apache.struts.action.ActionForm;
+import org.apache.struts.action.ActionForward;
+import org.apache.struts.action.ActionMapping;
+import org.lamsfoundation.lams.admin.service.AdminServiceProxy;
+import org.lamsfoundation.lams.learningdesign.LearningLibrary;
+import org.lamsfoundation.lams.learningdesign.LearningLibraryGroup;
+import org.lamsfoundation.lams.learningdesign.dto.LearningLibraryDTO;
+import org.lamsfoundation.lams.learningdesign.dto.LibraryActivityDTO;
+import org.lamsfoundation.lams.learningdesign.service.ILearningDesignService;
+import org.lamsfoundation.lams.tool.Tool;
+import org.lamsfoundation.lams.usermanagement.Role;
+import org.lamsfoundation.lams.usermanagement.dto.UserDTO;
+import org.lamsfoundation.lams.usermanagement.service.IUserManagementService;
+import org.lamsfoundation.lams.util.JsonUtil;
+import org.lamsfoundation.lams.util.WebUtil;
+import org.lamsfoundation.lams.web.session.SessionManager;
+import org.lamsfoundation.lams.web.util.AttributeNames;
+import org.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 jliew
+ *
+ *
+ *
+ *
+ *
+ *
+ */
+public class ToolContentListAction extends Action {
+
+ private static final String PARAM_ACTION = "action";
+ private static final String PARAM_LIBRARY_ID = "libraryID";
+
+ private static final String ATTRIBUTE_ERROR_NAME = "errorName";
+ private static final String ATTRIBUTE_ERROR_MESSAGE = "errorMessage";
+ private static final String ATTRIBUTE_LIBRARY = "toolLibrary";
+ private static final String ATTRIBUTE_VALIDITY = "learningLibraryValidity";
+ private static final String ATTRIBUTE_TOOL_VERSIONS = "toolVersions";
+ private static final String ATTRIBUTE_DATABASE_VERSIONS = "dbVersions";
+
+ private static final String FORWARD_SUCCESS = "toolcontentlist";
+ private static final String FORWARD_GROUPS = "groups";
+ private static final String FORWARD_ERROR = "error";
+
+ private static final String ACTION_ENABLE = "enable";
+ private static final String ACTION_DISABLE = "disable";
+ private static final String ACTION_OPEN_GROUPS = "openLearningLibraryGroups";
+ private static final String ACTION_SAVE_GROUPS = "saveLearningLibraryGroups";
+
+ private static final String QUERY_DATABASE_VERSIONS = "select system_name, patch_level from patches";
+
+ private static ILearningDesignService learningDesignService;
+ private static IUserManagementService userManagementService;
+ private static DataSource dataSource;
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) throws Exception {
+ // check permission
+ if (!(request.isUserInRole(Role.SYSADMIN))) {
+ request.setAttribute(ToolContentListAction.ATTRIBUTE_ERROR_NAME, "ToolContentListAction");
+ request.setAttribute(ToolContentListAction.ATTRIBUTE_ERROR_MESSAGE, AdminServiceProxy
+ .getMessageService(getServlet().getServletContext()).getMessage("error.authorisation"));
+ return mapping.findForward(ToolContentListAction.FORWARD_ERROR);
+ }
+
+ // not just display, but enable/disable a learning library
+ String param = request.getParameter(ToolContentListAction.PARAM_ACTION);
+ if (StringUtils.equals(param, ToolContentListAction.ACTION_ENABLE)) {
+ if (checkPriviledge(request)) {
+ enableLibrary(mapping, form, request, response);
+ } else {
+ return mapping.findForward(ToolContentListAction.FORWARD_ERROR);
+ }
+ } else if (StringUtils.equals(param, ToolContentListAction.ACTION_DISABLE)) {
+ if (checkPriviledge(request)) {
+ disableLibrary(mapping, form, request, response);
+ } else {
+ return mapping.findForward(ToolContentListAction.FORWARD_ERROR);
+ }
+ } else if (StringUtils.equals(param, ToolContentListAction.ACTION_OPEN_GROUPS)) {
+ return openLearningLibraryGroups(mapping, form, request, response);
+ } else if (StringUtils.equals(param, ToolContentListAction.ACTION_SAVE_GROUPS)) {
+ saveLearningLibraryGroups(mapping, form, request, response);
+ return null;
+ }
+
+ // get learning library dtos and their validity
+ List learningLibraryDTOs = getLearningDesignService().getAllLearningLibraryDetails(false,
+ getUserLanguage());
+ // this is filled when executing following method, for efficiency purposes
+ HashMap learningLibraryValidity = new HashMap(learningLibraryDTOs.size());
+ ArrayList toolLibrary = filterMultipleToolEntries(learningLibraryDTOs,
+ learningLibraryValidity);
+ request.setAttribute(ToolContentListAction.ATTRIBUTE_LIBRARY, toolLibrary);
+ request.setAttribute(ToolContentListAction.ATTRIBUTE_VALIDITY, learningLibraryValidity);
+
+ // get tool versions
+ HashMap toolVersions = new HashMap();
+ List tools = getUserManagementService().findAll(Tool.class);
+ for (Tool tool : tools) {
+ toolVersions.put(tool.getToolId(), tool.getToolVersion());
+ }
+ request.setAttribute(ToolContentListAction.ATTRIBUTE_TOOL_VERSIONS, toolVersions);
+
+ // get tool database versions
+ HashMap dbVersions = new HashMap();
+ Connection conn = getDataSource().getConnection();
+ PreparedStatement query = conn.prepareStatement(ToolContentListAction.QUERY_DATABASE_VERSIONS);
+ ResultSet results = query.executeQuery();
+ while (results.next()) {
+ dbVersions.put(results.getString("system_name"), results.getInt("patch_level"));
+ }
+ request.setAttribute(ToolContentListAction.ATTRIBUTE_DATABASE_VERSIONS, dbVersions);
+
+ return mapping.findForward(ToolContentListAction.FORWARD_SUCCESS);
+ }
+
+ // returns full list of learning libraries, valid or not
+ @SuppressWarnings("unchecked")
+ private ArrayList filterMultipleToolEntries(List learningLibraryDTOs,
+ HashMap learningLibraryValidity) {
+ ArrayList activeTools = new ArrayList();
+ ArrayList activeCombinedTools = new ArrayList();
+ for (LearningLibraryDTO learningLibraryDTO : learningLibraryDTOs) {
+ // populate information about learning libary validity
+ learningLibraryValidity.put(learningLibraryDTO.getLearningLibraryID(), learningLibraryDTO.getValidFlag());
+ for (LibraryActivityDTO template : (List) learningLibraryDTO.getTemplateActivities()) {
+ // no learning library ID = a part of combined learning library, we already have it in the list
+ if (template.getLearningLibraryID() != null) {
+ // combined libraries do not have tool content ID set
+ if (template.getToolContentID() == null) {
+ if (!toolExists(template, activeCombinedTools)) {
+ activeCombinedTools.add(template);
+ }
+ } else {
+ if (!toolExists(template, activeTools)) {
+ activeTools.add(template);
+ }
+ }
+ }
+ }
+ }
+ // put combined libraries at the end, purely for easy of use
+ activeTools.addAll(activeCombinedTools);
+ return activeTools;
+ }
+
+ private boolean toolExists(LibraryActivityDTO newItem, ArrayList list) {
+ for (LibraryActivityDTO libraryActivityDTO : list) {
+ if (newItem.getLearningLibraryID().equals(libraryActivityDTO.getLearningLibraryID())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private String getUserLanguage() {
+ HttpSession ss = SessionManager.getSession();
+ UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
+ return user == null ? "" : user.getLocaleLanguage();
+ }
+
+ private boolean checkPriviledge(HttpServletRequest request) {
+ if (!getUserManagementService().isUserSysAdmin()) {
+ request.setAttribute(ToolContentListAction.ATTRIBUTE_ERROR_NAME, "ToolContentListAction");
+ request.setAttribute(ToolContentListAction.ATTRIBUTE_ERROR_MESSAGE, AdminServiceProxy
+ .getMessageService(getServlet().getServletContext()).getMessage("error.no.sysadmin.priviledge"));
+ return false;
+ }
+ return true;
+ }
+
+ private void disableLibrary(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
+ Long learningLibraryId = WebUtil.readLongParam(request, ToolContentListAction.PARAM_LIBRARY_ID, false);
+ ILearningDesignService ldService = getLearningDesignService();
+ ldService.setValid(learningLibraryId, false);
+ }
+
+ private void enableLibrary(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) {
+ Long learningLibraryId = WebUtil.readLongParam(request, ToolContentListAction.PARAM_LIBRARY_ID, false);
+ ILearningDesignService ldService = getLearningDesignService();
+ ldService.setValid(learningLibraryId, true);
+
+ }
+
+ /**
+ * Loads groups and libraries and displays the management dialog.
+ */
+ private ActionForward openLearningLibraryGroups(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) throws IOException {
+ // build full list of available learning libraries
+ List learningLibraries = getLearningDesignService()
+ .getAllLearningLibraryDetails(getUserLanguage());
+ ArrayNode learningLibrariesJSON = JsonNodeFactory.instance.arrayNode();
+ for (LearningLibraryDTO learningLibrary : learningLibraries) {
+ ObjectNode learningLibraryJSON = JsonNodeFactory.instance.objectNode();
+ learningLibraryJSON.put("learningLibraryId", learningLibrary.getLearningLibraryID());
+ learningLibraryJSON.put("title", learningLibrary.getTitle());
+ learningLibrariesJSON.add(learningLibraryJSON);
+ }
+ request.setAttribute("learningLibraries", learningLibrariesJSON.toString());
+
+ // build list of existing groups
+ List groups = getLearningDesignService().getLearningLibraryGroups();
+ ArrayNode groupsJSON = JsonNodeFactory.instance.arrayNode();
+ for (LearningLibraryGroup group : groups) {
+ ObjectNode groupJSON = JsonNodeFactory.instance.objectNode();
+ groupJSON.put("groupId", group.getGroupId());
+ groupJSON.put("name", group.getName());
+ for (LearningLibrary learningLibrary : group.getLearningLibraries()) {
+ ObjectNode learningLibraryJSON = JsonNodeFactory.instance.objectNode();
+ learningLibraryJSON.put("learningLibraryId", learningLibrary.getLearningLibraryId());
+ learningLibraryJSON.put("title", learningLibrary.getTitle());
+ groupJSON.withArray("learningLibraries").add(learningLibraryJSON);
+ }
+ groupsJSON.add(groupJSON);
+ }
+ request.setAttribute("groups", groupsJSON.toString());
+
+ return mapping.findForward(ToolContentListAction.FORWARD_GROUPS);
+ }
+
+ private void saveLearningLibraryGroups(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) throws IOException {
+ // extract groups from JSON and persist them
+
+ ArrayNode groupsJSON = JsonUtil.readArray(request.getParameter("groups"));
+ List groups = new ArrayList<>(groupsJSON.size());
+ for (JsonNode groupJSON : groupsJSON) {
+ LearningLibraryGroup group = new LearningLibraryGroup();
+ groups.add(group);
+
+ long groupId = groupJSON.get("groupId").asLong();
+ if (groupId > 0) {
+ group.setGroupId(groupId);
+ }
+ group.setName(groupJSON.get("name").asText(null));
+
+ group.setLearningLibraries(new HashSet());
+ ArrayNode learningLibrariesJSON = (ArrayNode) groupJSON.get("learningLibraries");
+ for (JsonNode learningLibraryJSON : learningLibrariesJSON) {
+ long learningLibraryId = learningLibraryJSON.asLong();
+ LearningLibrary learningLibrary = getLearningDesignService().getLearningLibrary(learningLibraryId);
+ group.getLearningLibraries().add(learningLibrary);
+ }
+ }
+
+ getLearningDesignService().saveLearningLibraryGroups(groups);
+ }
+
+ private ILearningDesignService getLearningDesignService() {
+ if (ToolContentListAction.learningDesignService == null) {
+ WebApplicationContext ctx = WebApplicationContextUtils
+ .getRequiredWebApplicationContext(getServlet().getServletContext());
+ ToolContentListAction.learningDesignService = (ILearningDesignService) ctx.getBean("learningDesignService");
+ }
+ return ToolContentListAction.learningDesignService;
+ }
+
+ private IUserManagementService getUserManagementService() {
+ if (ToolContentListAction.userManagementService == null) {
+ WebApplicationContext ctx = WebApplicationContextUtils
+ .getRequiredWebApplicationContext(getServlet().getServletContext());
+ ToolContentListAction.userManagementService = (IUserManagementService) ctx.getBean("userManagementService");
+ }
+ return ToolContentListAction.userManagementService;
+ }
+
+ private DataSource getDataSource() {
+ if (ToolContentListAction.dataSource == null) {
+ WebApplicationContext ctx = WebApplicationContextUtils
+ .getRequiredWebApplicationContext(getServlet().getServletContext());
+ ToolContentListAction.dataSource = (DataSource) ctx.getBean("dataSource");
+ }
+ return ToolContentListAction.dataSource;
+ }
+}
\ No newline at end of file
Index: lams_admin/src/java/org/lamsfoundation/lams/admin/web/action/UserSearchAction.java
===================================================================
diff -u
--- lams_admin/src/java/org/lamsfoundation/lams/admin/web/action/UserSearchAction.java (revision 0)
+++ lams_admin/src/java/org/lamsfoundation/lams/admin/web/action/UserSearchAction.java (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -0,0 +1,157 @@
+/****************************************************************
+ * 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.admin.web.action;
+
+import java.io.IOException;
+import java.util.List;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.lang.StringEscapeUtils;
+import org.apache.log4j.Logger;
+import org.apache.struts.action.ActionForm;
+import org.apache.struts.action.ActionForward;
+import org.apache.struts.action.ActionMapping;
+
+
+import org.lamsfoundation.lams.admin.service.AdminServiceProxy;
+import org.lamsfoundation.lams.usermanagement.Role;
+import org.lamsfoundation.lams.usermanagement.dto.UserDTO;
+import org.lamsfoundation.lams.usermanagement.service.IUserManagementService;
+import org.lamsfoundation.lams.util.MessageService;
+import org.lamsfoundation.lams.util.WebUtil;
+import org.lamsfoundation.lams.web.action.LamsDispatchAction;
+
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+/**
+ * @author jliew
+ *
+ *
+ *
+ *
+ */
+public class UserSearchAction extends LamsDispatchAction {
+
+ private static Logger log = Logger.getLogger(UserSearchAction.class);
+ private static IUserManagementService service;
+ private static MessageService messageService;
+
+ @Override
+ public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse response) throws Exception {
+ initServices();
+
+ if (!(request.isUserInRole(Role.SYSADMIN) || service.isUserGlobalGroupAdmin())) {
+ log.debug("user not sysadmin or global group admin");
+
+ request.setAttribute("errorName", "UserSearchAction authorisation");
+ request.setAttribute("errorMessage", messageService.getMessage("error.authorisation"));
+ return mapping.findForward("error");
+ }
+
+ return mapping.findForward("usersearchlist");
+ }
+
+ /**
+ * Returns list of paged users.
+ */
+ public ActionForward getPagedUsers(ActionMapping mapping, ActionForm form, HttpServletRequest request,
+ HttpServletResponse res) throws IOException, ServletException {
+ initServices();
+
+ // the organisation type of the children
+ String searchString = WebUtil.readStrParam(request, "fcol[1]", true);
+
+ // paging parameters of tablesorter
+ int size = WebUtil.readIntParam(request, "size");
+ int page = WebUtil.readIntParam(request, "page");
+ Integer isSort1 = WebUtil.readIntParam(request, "column[0]", true);
+ Integer isSort2 = WebUtil.readIntParam(request, "column[1]", true);
+ Integer isSort3 = WebUtil.readIntParam(request, "column[2]", true);
+ Integer isSort4 = WebUtil.readIntParam(request, "column[3]", true);
+ Integer isSort5 = WebUtil.readIntParam(request, "column[4]", true);
+
+ String sortBy = "userId";
+ String sortOrder = "DESC";
+ if (isSort1 != null) {
+ sortBy = "userId";
+ sortOrder = isSort1.equals(0) ? "ASC" : "DESC";
+
+ } else if (isSort2 != null) {
+ sortBy = "login";
+ sortOrder = isSort2.equals(0) ? "ASC" : "DESC";
+
+ } else if (isSort3 != null) {
+ sortBy = "firstName";
+ sortOrder = isSort3.equals(0) ? "ASC" : "DESC";
+
+ } else if (isSort4 != null) {
+ sortBy = "lastName";
+ sortOrder = isSort4.equals(0) ? "ASC" : "DESC";
+
+ } else if (isSort5 != null) {
+ sortBy = "email";
+ sortOrder = isSort5.equals(0) ? "ASC" : "DESC";
+ }
+
+ List userDtos = service.getAllUsersPaged(page, size, sortBy, sortOrder, searchString);
+
+ ObjectNode responcedata = JsonNodeFactory.instance.objectNode();
+ responcedata.put("total_rows", service.getCountUsers(searchString));
+
+ ArrayNode rows = JsonNodeFactory.instance.arrayNode();
+ for (UserDTO userDto : userDtos) {
+ ObjectNode responseRow = JsonNodeFactory.instance.objectNode();
+ responseRow.put("userId", userDto.getUserID());
+ responseRow.put("login", StringEscapeUtils.escapeHtml(userDto.getLogin()));
+ String firstName = userDto.getFirstName() == null ? "" : userDto.getFirstName();
+ responseRow.put("firstName", StringEscapeUtils.escapeHtml(firstName));
+ String lastName = userDto.getLastName() == null ? "" : userDto.getLastName();
+ responseRow.put("lastName", StringEscapeUtils.escapeHtml(lastName));
+ String email = userDto.getEmail() == null ? "" : userDto.getEmail();
+ responseRow.put("email", StringEscapeUtils.escapeHtml(email));
+
+ rows.add(responseRow);
+ }
+ responcedata.set("rows", rows);
+ res.setContentType("application/json;charset=utf-8");
+ res.getWriter().print(new String(responcedata.toString()));
+ return null;
+ }
+
+ private void initServices() {
+ if (service == null) {
+ service = AdminServiceProxy.getService(getServlet().getServletContext());
+ }
+ if (messageService == null) {
+ messageService = AdminServiceProxy.getMessageService(getServlet().getServletContext());
+ }
+ }
+
+}
\ No newline at end of file
Index: lams_build/build_base.xml
===================================================================
diff -u -r0b67ee804237056395e60ed4cca2948a595ddb72 -r2c03060b238558d183472f0066ba003c76d00fd0
--- lams_build/build_base.xml (.../build_base.xml) (revision 0b67ee804237056395e60ed4cca2948a595ddb72)
+++ lams_build/build_base.xml (.../build_base.xml) (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -41,7 +41,6 @@
-
@@ -55,6 +54,8 @@
+
+
Index: lams_build/common.properties
===================================================================
diff -u -r6d0fd60838e941efefda00d1dd9778accf37a4b7 -r2c03060b238558d183472f0066ba003c76d00fd0
--- lams_build/common.properties (.../common.properties) (revision 6d0fd60838e941efefda00d1dd9778accf37a4b7)
+++ lams_build/common.properties (.../common.properties) (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -18,7 +18,7 @@
# http://www.gnu.org/licenses/gpl.txt
# put into EAR MANIFEST.MF file
-project.version=3.0
+project.version=3.1
# is HTTPS in use? if so, set it to true, so JSESSIONID cookie is secured
secure.cookie=false
Index: lams_build/lib/lams/lams.jar
===================================================================
diff -u -r953f62a7fc515e2dc5c4ad983df233070cf7a82c -r2c03060b238558d183472f0066ba003c76d00fd0
Binary files differ
Index: lams_build/liblist.txt
===================================================================
diff -u -r6d0fd60838e941efefda00d1dd9778accf37a4b7 -r2c03060b238558d183472f0066ba003c76d00fd0
--- lams_build/liblist.txt (.../liblist.txt) (revision 6d0fd60838e941efefda00d1dd9778accf37a4b7)
+++ lams_build/liblist.txt (.../liblist.txt) (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -2,10 +2,10 @@
Folder Library Version License Vendor Description
-apache-poi poi-3.10-FINAL-20140208.jar 3.10 Apache License 2.0 Apache the Java API for Microsoft Documents
- poi-ooxml-3.10-FINAL-20140208.jar
- poi-ooxml-schemas-3.10-FINAL-20140208.jar
- xmlbeans-2.4.0.jar 2.3.0
+apache-poi poi-3.16.jar 3.16 Apache License 2.0 Apache the Java API for Microsoft Documents
+ poi-ooxml-3.16.jar
+ poi-ooxml-schemas-3.16.jar
+ xmlbeans-2.6.0.jar 2.6.0
autopatch autopatch-1.4.2-lams.jar 1.4.2-lams Apache License Tacit Knowledge automated Java patching system
discovery-1.0.5-lams.jar 1.0.5-lams
@@ -23,46 +23,36 @@
googleauth googleauth-1.1.1.jar 1.1.1 Public Domain Enrico M. Crisostomo Java server library that implements the Time-based One-time Password (TOTP) algorithm
jakarta-commons commons-digester-2.1.jar 2.1 Apache Software License 2.0 Apache Software Foundation XML -> Java object mapping tool
- commons-fileupload.jar 1.0 Apache Software License 1.1 Apache Software Foundation File upload component for Java servlets
- commons-validator.jar 1.1.4 Apache License 2.0 The Apache Software Foundation Commons Validator
+ commons-fileupload-1.3.3.jar 1.3.3 Apache Software License 1.1 Apache Software Foundation File upload component for Java servlets
+ commons-validator-1.6.jar 1.6 Apache License 2.0 The Apache Software Foundation Commons Validator
+ commons-discovery-0.5.jar 0.5 Apache License 2.0 The Apache Software Foundation
-jboss jbossweb.jar 2.1.3 LGPL 2.1 Apache Software Foundation SSO valve and JSON
-
-jlatexmath jlatexmath-1.0.3.jar 1.0.3
+jlatexmath jlatexmath-1.0.6.jar 1.0.6
json-simple json-simple-1.1.1.jar 1.1.1 Apache License 2.0 fangyidong A simple Java toolkit for JSON
-lucene lucene-core-2.4.0.jar 2.4.0 Apache License 2.0 Apache text search engine library
- lucene-snowball-2.4.0.jar 2.4.0
+mysql mysql-connector-java-5.1.43-bin.jar 5.1.43 GPL Oracle Java connector for MySQL
-mysql mysql-connector-java-5.1.38-bin.jar 5.1.31 GPL Oracle Java connector for MySQL
-
odmg odmg-3.0.jar 3.0
-quartz quartz-2.2.1.jar 2.2.1 Apache License 2.0 Terracotta For running scheduled jobs
+quartz quartz-2.2.3.jar 2.2.3 Apache License 2.0 Terracotta For running scheduled jobs
-spring spring-core-4.0.6.RELEASE.jar 4.0.6 Apache License 2.0 GoPivotal programming and configuration model for modern Java-based enterprise applications
- spring-beans-4.0.6.RELEASE.jar
- spring-context-4.0.6.RELEASE.jar
- spring-context-support-4.0.6.RELEASE.jar
- spring-expression-4.0.6.RELEASE.jar
- spring-jdbc-4.0.6.RELEASE.jar
- spring-orm-4.0.6.RELEASE.jar
- spring-tx-4.0.6.RELEASE.jar
- spring-web-4.0.6.RELEASE.jar
- aopalliance.jar 1.0 Public Domain AOP Alliance
+spring spring-core-4.3.10.RELEASE.jar 4.3.10 Apache License 2.0 Pivotal programming and configuration model for modern Java-based enterprise applications
+ spring-beans-4.3.10.RELEASE.jar
+ spring-context-4.3.10.RELEASE.jar
+ spring-context-support-4.3.10.RELEASE.jar
+ spring-expression-4.3.10.RELEASE.jar
+ spring-jdbc-4.3.10.RELEASE.jar
+ spring-orm-4.3.10.RELEASE.jar
+ spring-tx-4.3.10.RELEASE.jar
+ spring-web-4.3.10.RELEASE.jar
struts jakarta-oro.jar 2.0.7 Apache License 2.0 Apache regular expressions
struts.jar 1.2.7 Apache License 2.0 Apache Struts Framework
struts-el.jar 1.2.9 Apache License 2.0 Apache Struts extensions
urlrewritefilter urlrewritefilter-4.0.3.jar 4.0.3 BSD License tuckey.org Java Web Filter which allows rewriting URLs
-xml-commons xml-apis.jar 1.3
- xml-apis-ext.jar 1.3 Apache License 2.0 Apache Common code and guidelines for xml projects
+xstream xstream-1.5.0-SNAPSHOT.jar 1.5.0 XML serializer
-xstream xmlpull-1.1.3.1.jar 1.1.3.1
- xpp3_min-1.1.4c.jar 1.1.4c
- xstream-1.5.0-SNAPSHOT.jar 1.5.0 XML serializer
-
yuicompressor yuicompressor-2.4.9 2.4.9 BSD License YUI CSS and JS minifier
Index: lams_central/src/java/org/lamsfoundation/lams/web/HomeAction.java
===================================================================
diff -u -rb67c428939ed96f08f56192d54b8ee55d8ab89d2 -r2c03060b238558d183472f0066ba003c76d00fd0
--- lams_central/src/java/org/lamsfoundation/lams/web/HomeAction.java (.../HomeAction.java) (revision b67c428939ed96f08f56192d54b8ee55d8ab89d2)
+++ lams_central/src/java/org/lamsfoundation/lams/web/HomeAction.java (.../HomeAction.java) (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -27,9 +27,6 @@
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
-import java.net.URLEncoder;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.TreeSet;
@@ -46,8 +43,6 @@
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
-import org.apache.tomcat.util.json.JSONException;
-import org.apache.tomcat.util.json.JSONObject;
import org.lamsfoundation.lams.contentrepository.exception.RepositoryCheckedException;
import org.lamsfoundation.lams.learningdesign.GroupUser;
import org.lamsfoundation.lams.learningdesign.dao.IGroupUserDAO;
@@ -75,6 +70,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;
+
/**
* This is an action where all lams client environments launch. initial configuration of the individual environment
* setting is done here.
@@ -176,7 +174,6 @@
return mapping.findForward("lessonIntro");
}
-
if (mode != null) {
req.setAttribute(AttributeNames.PARAM_MODE, mode);
}
@@ -187,7 +184,7 @@
: "/" + serverURLContextPath;
serverURLContextPath += serverURLContextPath.endsWith("/") ? "" : "/";
getServlet().getServletContext().getContext(serverURLContextPath + "learning")
- .getRequestDispatcher("/content.do?lessonID="+lessonId).forward(req, res);
+ .getRequestDispatcher("/content.do?lessonID=" + lessonId).forward(req, res);
return null;
} catch (Exception e) {
@@ -241,8 +238,7 @@
@SuppressWarnings("unchecked")
public ActionForward addLesson(ActionMapping mapping, ActionForm form, HttpServletRequest req,
- HttpServletResponse res)
- throws IOException, UserAccessDeniedException, JSONException, RepositoryCheckedException {
+ HttpServletResponse res) throws IOException, UserAccessDeniedException, RepositoryCheckedException {
UserDTO userDTO = getUser();
Integer organisationID = new Integer(WebUtil.readIntParam(req, "organisationID"));
@@ -255,35 +251,35 @@
String folderContentsJSON = getWorkspaceManagementService().getFolderContentsJSON(null, userDTO.getUserID(),
false);
req.setAttribute("folderContents", folderContentsJSON);
- JSONObject users = new JSONObject();
+ ObjectNode users = JsonNodeFactory.instance.objectNode();
// get learners available for newly created lesson
Vector learners = getUserManagementService().getUsersFromOrganisationByRole(organisationID, "LEARNER",
true);
for (User user : learners) {
- JSONObject userJSON = new JSONObject();
+ ObjectNode userJSON = JsonNodeFactory.instance.objectNode();
userJSON.put("userID", user.getUserId());
userJSON.put("firstName", user.getFirstName());
userJSON.put("lastName", user.getLastName());
userJSON.put("login", user.getLogin());
- users.append("selectedLearners", userJSON);
+ users.withArray("selectedLearners").add(userJSON);
}
Vector monitors = getUserManagementService().getUsersFromOrganisationByRole(organisationID, "MONITOR",
true);
for (User user : monitors) {
- JSONObject userJSON = new JSONObject();
+ ObjectNode userJSON = JsonNodeFactory.instance.objectNode();
userJSON.put("userID", user.getUserId());
userJSON.put("firstName", user.getFirstName());
userJSON.put("lastName", user.getLastName());
userJSON.put("login", user.getLogin());
if (userDTO.getUserID().equals(user.getUserId())) {
// creator is always selected
- users.append("selectedMonitors", userJSON);
+ users.withArray("selectedMonitors").add(userJSON);
} else {
- users.append("unselectedMonitors", userJSON);
+ users.withArray("unselectedMonitors").add(userJSON);
}
}
@@ -292,7 +288,7 @@
// find lessons which can be set as preceding ones for newly created lesson
Organisation organisation = (Organisation) getUserManagementService().findById(Organisation.class,
organisationID);
- Set availableLessons = new TreeSet(new LessonDTOComparator());
+ Set availableLessons = new TreeSet<>(new LessonDTOComparator());
for (Lesson availableLesson : (Set) organisation.getLessons()) {
Integer availableLessonState = availableLesson.getLessonStateId();
if (!Lesson.REMOVED_STATE.equals(availableLessonState)
@@ -309,8 +305,7 @@
* Gets subfolder contents in Add Lesson screen.
*/
public ActionForward getFolderContents(ActionMapping mapping, ActionForm form, HttpServletRequest req,
- HttpServletResponse res)
- throws UserAccessDeniedException, JSONException, IOException, RepositoryCheckedException {
+ HttpServletResponse res) throws UserAccessDeniedException, IOException, RepositoryCheckedException {
Integer folderID = WebUtil.readIntParam(req, "folderID", true);
boolean allowInvalidDesigns = WebUtil.readBooleanParam(req, "allowInvalidDesigns", false);
String folderContentsJSON = getWorkspaceManagementService().getFolderContentsJSON(folderID,
Index: lams_central/src/java/org/lamsfoundation/lams/web/IndexAction.java
===================================================================
diff -u -r9b24f3330d42579e9c7b3e807568360a617d9a8c -r2c03060b238558d183472f0066ba003c76d00fd0
--- lams_central/src/java/org/lamsfoundation/lams/web/IndexAction.java (.../IndexAction.java) (revision 9b24f3330d42579e9c7b3e807568360a617d9a8c)
+++ lams_central/src/java/org/lamsfoundation/lams/web/IndexAction.java (.../IndexAction.java) (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -38,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.index.IndexLinkBean;
import org.lamsfoundation.lams.usermanagement.Organisation;
import org.lamsfoundation.lams.usermanagement.Role;
@@ -57,6 +54,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 Fei Yang
@@ -74,7 +75,7 @@
public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
- setHeaderLinks(request);
+ IndexAction.setHeaderLinks(request);
setAdminLinks(request);
// check if this is user's first login; some action (like displaying a dialog for disabling tutorials) can be
@@ -111,25 +112,26 @@
return mapping.findForward("editprofile");
} else if (StringUtils.equals(method, "password")) {
return mapping.findForward("password");
- } else if (StringUtils.equals(method, "portrait")) {
+ } else if (StringUtils.equals(method, "portrait")) {
return mapping.findForward("portrait");
} else if (StringUtils.equals(method, "lessons")) {
return mapping.findForward("lessons");
}
-
+
// only show the growl warning the first time after a user has logged in & if turned on in configuration
Boolean tzWarning = Configuration.getAsBoolean(ConfigurationKeys.SHOW_TIMEZONE_WARNING);
request.setAttribute("showTimezoneWarning", tzWarning);
request.setAttribute("showTimezoneWarningPopup", false);
- if ( tzWarning ) {
+ if (tzWarning) {
Boolean ssWarningShown = (Boolean) ss.getAttribute("timezoneWarningShown");
- if ( ! Boolean.TRUE.equals(ssWarningShown) ) {
+ if (!Boolean.TRUE.equals(ssWarningShown)) {
ss.setAttribute("timezoneWarningShown", Boolean.TRUE);
request.setAttribute("showTimezoneWarningPopup", true);
}
}
-
- List favoriteOrganisations = userManagementService.getFavoriteOrganisationsByUser(userDTO.getUserID());
+
+ List favoriteOrganisations = userManagementService
+ .getFavoriteOrganisationsByUser(userDTO.getUserID());
request.setAttribute("favoriteOrganisations", favoriteOrganisations);
request.setAttribute("activeOrgId", user.getLastVisitedOrganisationId());
@@ -141,9 +143,9 @@
}
private static void setHeaderLinks(HttpServletRequest request) {
- List headerLinks = new ArrayList();
+ List headerLinks = new ArrayList<>();
if (request.isUserInRole(Role.AUTHOR)) {
- if (isPedagogicalPlannerAvailable()) {
+ if (IndexAction.isPedagogicalPlannerAvailable()) {
headerLinks.add(new IndexLinkBean("index.planner", "javascript:openPedagogicalPlanner()"));
}
headerLinks.add(new IndexLinkBean("index.author", "javascript:showAuthoringDialog()"));
@@ -159,7 +161,7 @@
}
private void setAdminLinks(HttpServletRequest request) {
- List adminLinks = new ArrayList();
+ List adminLinks = new ArrayList<>();
if (request.isUserInRole(Role.SYSADMIN) || request.isUserInRole(Role.GROUP_ADMIN)
|| request.isUserInRole(Role.GROUP_MANAGER)) {
adminLinks.add(new IndexLinkBean("index.courseman", "javascript:openOrgManagement("
@@ -175,10 +177,10 @@
* Returns list of organisations for user. Used by offcanvas tablesorter on main.jsp.
*/
public ActionForward getOrgs(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse res) throws IOException, ServletException, JSONException {
+ HttpServletResponse res) throws IOException, ServletException {
getUserManagementService();
User loggedInUser = getUserManagementService().getUserByLogin(request.getRemoteUser());
-
+
Integer userId = loggedInUser.getUserId();
boolean isSysadmin = request.isUserInRole(Role.SYSADMIN);
String searchString = WebUtil.readStrParam(request, "fcol[1]", true);
@@ -199,27 +201,28 @@
//
// }
- List orgDtos = userManagementService.getActiveCoursesByUser(userId, isSysadmin, page, size, searchString);
+ List orgDtos = userManagementService.getActiveCoursesByUser(userId, isSysadmin, page, size,
+ searchString);
- JSONObject responcedata = new JSONObject();
- responcedata.put("total_rows", userManagementService.getCountActiveCoursesByUser(userId, isSysadmin, searchString));
+ ObjectNode responcedata = JsonNodeFactory.instance.objectNode();
+ responcedata.put("total_rows",
+ userManagementService.getCountActiveCoursesByUser(userId, isSysadmin, searchString));
- JSONArray rows = new JSONArray();
+ ArrayNode rows = JsonNodeFactory.instance.arrayNode();
for (OrganisationDTO orgDto : orgDtos) {
-
- JSONObject responseRow = new JSONObject();
+ ObjectNode responseRow = JsonNodeFactory.instance.objectNode();
responseRow.put("id", orgDto.getOrganisationID());
String orgName = orgDto.getName() == null ? "" : orgDto.getName();
responseRow.put("name", StringEscapeUtils.escapeHtml(orgName));
- rows.put(responseRow);
+ rows.add(responseRow);
}
- responcedata.put("rows", rows);
+ responcedata.set("rows", rows);
res.setContentType("application/json;charset=utf-8");
res.getWriter().print(new String(responcedata.toString()));
return null;
}
-
+
/**
* Toggles whether organisation is marked as favorite.
*/
@@ -235,18 +238,18 @@
List favoriteOrganisations = userManagementService.getFavoriteOrganisationsByUser(userId);
request.setAttribute("favoriteOrganisations", favoriteOrganisations);
-
+
String activeOrgId = request.getParameter("activeOrgId");
request.setAttribute("activeOrgId", activeOrgId);
return mapping.findForward("favoriteOrganisations");
}
-
+
/**
* Saves to DB last visited organisation. It's required for displaying some org on main.jsp next time user logs in.
*/
- public ActionForward storeLastVisitedOrganisation(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse res) throws IOException, ServletException {
+ public ActionForward storeLastVisitedOrganisation(ActionMapping mapping, ActionForm form,
+ HttpServletRequest request, HttpServletResponse res) throws IOException, ServletException {
getUserManagementService();
Integer lastVisitedOrganisationId = WebUtil.readIntParam(request, "orgId", false);
@@ -259,7 +262,7 @@
return null;
}
-
+
private Integer getUserId() {
HttpSession ss = SessionManager.getSession();
UserDTO learner = (UserDTO) ss.getAttribute(AttributeNames.USER);
Index: lams_central/src/java/org/lamsfoundation/lams/web/OrganisationGroupAction.java
===================================================================
diff -u -rb67c428939ed96f08f56192d54b8ee55d8ab89d2 -r2c03060b238558d183472f0066ba003c76d00fd0
--- lams_central/src/java/org/lamsfoundation/lams/web/OrganisationGroupAction.java (.../OrganisationGroupAction.java) (revision b67c428939ed96f08f56192d54b8ee55d8ab89d2)
+++ lams_central/src/java/org/lamsfoundation/lams/web/OrganisationGroupAction.java (.../OrganisationGroupAction.java) (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -44,9 +44,6 @@
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
-import org.apache.tomcat.util.json.JSONArray;
-import org.apache.tomcat.util.json.JSONException;
-import org.apache.tomcat.util.json.JSONObject;
import org.lamsfoundation.lams.contentrepository.exception.InvalidParameterException;
import org.lamsfoundation.lams.integration.dto.ExtGroupDTO;
import org.lamsfoundation.lams.integration.service.IIntegrationService;
@@ -71,12 +68,19 @@
import org.lamsfoundation.lams.usermanagement.dto.UserDTO;
import org.lamsfoundation.lams.usermanagement.service.IUserManagementService;
import org.lamsfoundation.lams.util.AlphanumComparator;
+import org.lamsfoundation.lams.util.JsonUtil;
import org.lamsfoundation.lams.util.WebUtil;
import org.lamsfoundation.lams.web.session.SessionManager;
import org.lamsfoundation.lams.web.util.AttributeNames;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
public class OrganisationGroupAction extends DispatchAction {
private static Logger log = Logger.getLogger(OrganisationGroupAction.class);
@@ -215,7 +219,7 @@
Long activityId = WebUtil.readLongParam(request, AttributeNames.PARAM_ACTIVITY_ID, true);
request.setAttribute("canEdit", isGroupSuperuser || (activityId != null));
- JSONObject orgGroupingJSON = new JSONObject();
+ ObjectNode orgGroupingJSON = JsonNodeFactory.instance.objectNode();
orgGroupingJSON.put("organisationId", organisationId);
Long orgGroupingId = WebUtil.readLongParam(request, "groupingId", true);
@@ -259,7 +263,7 @@
boolean isUsedForBranching = (lessonGrouping != null) && lessonGrouping.isUsedForBranching();
request.setAttribute(GroupingAJAXAction.PARAM_USED_FOR_BRANCHING, isUsedForBranching);
- JSONArray orgGroupsJSON = new JSONArray();
+ ArrayNode orgGroupsJSON = JsonNodeFactory.instance.arrayNode();
Collection learners = null;
// if teacher selected groups from integrated server - show them
@@ -299,19 +303,19 @@
// sort groups by their name
Collections.sort(extGroups);
for (ExtGroupDTO extGroup : extGroups) {
- JSONObject groupJSON = new JSONObject();
+ ObjectNode groupJSON = JsonNodeFactory.instance.objectNode();
groupJSON.put("name", extGroup.getGroupName());
groupJSON.put("groupId", extGroup.getGroupId());
if (extGroup.getUsers() != null) {
for (User groupUser : (List) extGroup.getUsers()) {
- JSONObject groupUserJSON = WebUtil.userToJSON(groupUser);
- groupJSON.append("users", groupUserJSON);
+ ObjectNode groupUserJSON = WebUtil.userToJSON(groupUser);
+ groupJSON.withArray("users").add(groupUserJSON);
// remove the user who is already assigned to a group
learners.remove(groupUser);
}
}
- orgGroupsJSON.put(groupJSON);
+ orgGroupsJSON.add(groupJSON);
}
}
@@ -332,14 +336,14 @@
orgGroupsJSON = getLessonGroupsDetails(lessonGroups, learners);
request.setAttribute("skipInitialAssigning", true);
}
- orgGroupingJSON.put("groups", orgGroupsJSON);
+ orgGroupingJSON.set("groups", orgGroupsJSON);
request.setAttribute("grouping", orgGroupingJSON);
// all the remaining users are unassigned to any group
- JSONArray unassignedUsersJSON = new JSONArray();
+ ArrayNode unassignedUsersJSON = JsonNodeFactory.instance.arrayNode();
for (User unassignedUser : learners) {
- JSONObject unassignedUserJSON = WebUtil.userToJSON(unassignedUser);
- unassignedUsersJSON.put(unassignedUserJSON);
+ ObjectNode unassignedUserJSON = WebUtil.userToJSON(unassignedUser);
+ unassignedUsersJSON.add(unassignedUserJSON);
}
request.setAttribute("unassignedUsers", unassignedUsersJSON);
@@ -350,7 +354,7 @@
* Saves a course grouping.
*/
public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) throws JSONException, InvalidParameterException, IOException {
+ HttpServletResponse response) throws InvalidParameterException, IOException {
// check if user is allowed to edit groups
Integer userId = getUserDTO().getUserID();
int organisationId = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID);
@@ -367,38 +371,37 @@
}
// deserialize grouping
- JSONObject orgGroupingJSON = new JSONObject(request.getParameter("grouping"));
+ ObjectNode orgGroupingJSON = new ObjectMapper().readValue(request.getParameter("grouping"), ObjectNode.class);
// check if already exists
- Long orgGroupingId = orgGroupingJSON.optLong("groupingId");
+ Long orgGroupingId = orgGroupingJSON.get("groupingId").asLong();
if (orgGroupingId == 0L) {
orgGroupingId = null;
}
// iterate over groups
List orgGroups = new LinkedList<>();
- JSONArray orgGroupsJSON = orgGroupingJSON.optJSONArray("groups");
+ ArrayNode orgGroupsJSON = JsonUtil.optArray(orgGroupingJSON, "groups");
if (orgGroupsJSON != null) {
- for (int i = 0; i < orgGroupsJSON.length(); i++) {
+ for (JsonNode orgGroupNode : orgGroupsJSON) {
// just overwrite existing groups; they will be updated if already exist
Set users = new HashSet<>();
- JSONObject orgGroupJSON = orgGroupsJSON.getJSONObject(i);
- JSONArray usersJSON = orgGroupJSON.optJSONArray("users");
+ ObjectNode orgGroupJSON = (ObjectNode) orgGroupNode;
+ ArrayNode usersJSON = JsonUtil.optArray(orgGroupJSON, "users");
if (usersJSON != null) {
// find user objects based on delivered IDs
- for (int j = 0; j < usersJSON.length(); j++) {
- Integer learnerId = usersJSON.getInt(j);
- User user = (User) getUserManagementService().findById(User.class, learnerId);
+ for (JsonNode learnerId : usersJSON) {
+ User user = (User) getUserManagementService().findById(User.class, learnerId.asInt());
users.add(user);
}
}
OrganisationGroup orgGroup = new OrganisationGroup();
- Long orgGroupId = orgGroupJSON.optLong("groupId");
+ Long orgGroupId = JsonUtil.optLong(orgGroupJSON, "groupId");
if (orgGroupId > 0) {
orgGroup.setGroupId(orgGroupId);
orgGroup.setGroupingId(orgGroupingId);
}
- orgGroup.setName(orgGroupJSON.optString("name", null));
+ orgGroup.setName(JsonUtil.optString(orgGroupJSON, "name"));
orgGroup.setUsers(users);
orgGroups.add(orgGroup);
@@ -415,7 +418,7 @@
orgGrouping.setOrganisationId(organisationId);
}
// update grouping name
- String orgGroupingName = orgGroupingJSON.getString("name");
+ String orgGroupingName = JsonUtil.optString(orgGroupingJSON, "name");
orgGrouping.setName(orgGroupingName);
getUserManagementService().saveOrganisationGrouping(orgGrouping, orgGroups);
@@ -452,36 +455,36 @@
* Fetches course and branching so they can get matched by user.
*/
public ActionForward getGroupsForMapping(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) throws IOException, JSONException {
+ HttpServletResponse response) throws IOException {
Long orgGroupingId = WebUtil.readLongParam(request, "groupingId");
Long activityID = WebUtil.readLongParam(request, AttributeNames.PARAM_ACTIVITY_ID);
OrganisationGrouping orgGrouping = (OrganisationGrouping) getUserManagementService()
.findById(OrganisationGrouping.class, orgGroupingId);
- JSONArray groupsJSON = new JSONArray();
+ ArrayNode groupsJSON = JsonNodeFactory.instance.arrayNode();
SortedSet orgGroups = new TreeSet<>(orgGrouping.getGroups());
for (OrganisationGroup group : orgGroups) {
- JSONObject groupJSON = new JSONObject();
+ ObjectNode groupJSON = JsonNodeFactory.instance.objectNode();
groupJSON.put("id", group.getGroupId());
groupJSON.put("name", group.getName());
- groupsJSON.put(groupJSON);
+ groupsJSON.add(groupJSON);
}
Activity activity = (Activity) getUserManagementService().findById(Activity.class, activityID);
Grouping grouping = activity.isGroupingActivity() ? ((GroupingActivity) activity).getCreateGrouping()
: ((BranchingActivity) activity).getGrouping();
- JSONArray branchesJSON = new JSONArray();
+ ArrayNode branchesJSON = JsonNodeFactory.instance.arrayNode();
SortedSet groups = new TreeSet<>(grouping.getGroups());
for (Group group : groups) {
- JSONObject groupJSON = new JSONObject();
+ ObjectNode groupJSON = JsonNodeFactory.instance.objectNode();
groupJSON.put("id", group.getGroupId());
groupJSON.put("name", group.getGroupName());
- branchesJSON.put(groupJSON);
+ branchesJSON.add(groupJSON);
}
- JSONObject responseJSON = new JSONObject();
- responseJSON.put("branches", branchesJSON);
- responseJSON.put("groups", groupsJSON);
+ ObjectNode responseJSON = JsonNodeFactory.instance.objectNode();
+ responseJSON.set("branches", branchesJSON);
+ responseJSON.set("groups", groupsJSON);
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(responseJSON.toString());
@@ -492,12 +495,12 @@
* Stores course groups to branching groups mapping.
*/
public ActionForward saveGroupMappings(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) throws IOException, JSONException {
- JSONArray groupMapping = new JSONArray(request.getParameter("mapping"));
- for (int index = 0; index < groupMapping.length(); index++) {
- JSONObject entry = groupMapping.getJSONObject(index);
- Long orgGroupID = entry.getLong("groupID");
- Long branchingGroupID = entry.getLong("branchID");
+ HttpServletResponse response) throws IOException {
+ ArrayNode groupMapping = JsonUtil.readArray(request.getParameter("mapping"));
+ for (JsonNode entryNode : groupMapping) {
+ ObjectNode entry = (ObjectNode) entryNode;
+ Long orgGroupID = JsonUtil.optLong(entry, "groupID");
+ Long branchingGroupID = JsonUtil.optLong(entry, "branchID");
OrganisationGroup orgGroup = (OrganisationGroup) getUserManagementService()
.findById(OrganisationGroup.class, orgGroupID);
Group branchingGroup = (Group) getUserManagementService().findById(Group.class, branchingGroupID);
@@ -514,28 +517,28 @@
/**
* Build JSON objects based on existing lesson-level groups.
*/
- private JSONArray getLessonGroupsDetails(Set groups, Collection learners) throws JSONException {
+ private ArrayNode getLessonGroupsDetails(Set groups, Collection learners) {
// serialize database group objects into JSON
- JSONArray groupsJSON = new JSONArray();
+ ArrayNode groupsJSON = JsonNodeFactory.instance.arrayNode();
if (groups != null) {
// sort groups by their name
List groupList = new LinkedList<>(groups);
Collections.sort(groupList, new GroupComparator());
for (Group group : groupList) {
- JSONObject groupJSON = new JSONObject();
+ ObjectNode groupJSON = JsonNodeFactory.instance.objectNode();
groupJSON.put("name", group.getGroupName());
groupJSON.put("groupId", group.getGroupId());
groupJSON.put("locked", !group.mayBeDeleted());
if (group.getUsers() != null) {
for (User groupUser : group.getUsers()) {
- JSONObject groupUserJSON = WebUtil.userToJSON(groupUser);
- groupJSON.append("users", groupUserJSON);
+ ObjectNode groupUserJSON = WebUtil.userToJSON(groupUser);
+ groupJSON.withArray("users").add(groupUserJSON);
// remove the user who is already assigned to a group
learners.remove(groupUser);
}
}
- groupsJSON.put(groupJSON);
+ groupsJSON.add(groupJSON);
}
}
@@ -545,8 +548,7 @@
/**
* Build JSON objects based on existing course-level groups.
*/
- private JSONArray getOrgGroupsDetails(Set groups, Collection learners)
- throws JSONException {
+ private ArrayNode getOrgGroupsDetails(Set groups, Collection learners) {
final Comparator ORG_GROUP_COMPARATOR = new Comparator() {
@Override
@@ -560,25 +562,25 @@
};
// serialize database group objects into JSON
- JSONArray groupsJSON = new JSONArray();
+ ArrayNode groupsJSON = JsonNodeFactory.instance.arrayNode();
if (groups != null) {
// sort groups by their name
List groupList = new LinkedList<>(groups);
Collections.sort(groupList, ORG_GROUP_COMPARATOR);
for (OrganisationGroup group : groupList) {
- JSONObject groupJSON = new JSONObject();
+ ObjectNode groupJSON = JsonNodeFactory.instance.objectNode();
groupJSON.put("name", group.getName());
groupJSON.put("groupId", group.getGroupId());
for (User groupUser : group.getUsers()) {
- JSONObject groupUserJSON = WebUtil.userToJSON(groupUser);
- groupJSON.append("users", groupUserJSON);
+ ObjectNode groupUserJSON = WebUtil.userToJSON(groupUser);
+ groupJSON.withArray("users").add(groupUserJSON);
// remove the user who is already assigned to a group
learners.remove(groupUser);
}
- groupsJSON.put(groupJSON);
+ groupsJSON.add(groupJSON);
}
}
Index: lams_central/src/java/org/lamsfoundation/lams/web/action/LtiAction.java
===================================================================
diff -u -rb67c428939ed96f08f56192d54b8ee55d8ab89d2 -r2c03060b238558d183472f0066ba003c76d00fd0
--- lams_central/src/java/org/lamsfoundation/lams/web/action/LtiAction.java (.../LtiAction.java) (revision b67c428939ed96f08f56192d54b8ee55d8ab89d2)
+++ lams_central/src/java/org/lamsfoundation/lams/web/action/LtiAction.java (.../LtiAction.java) (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -15,7 +15,7 @@
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionRedirect;
-import org.apache.tomcat.util.json.JSONException;
+
import org.imsglobal.lti.BasicLTIConstants;
import org.lamsfoundation.lams.contentrepository.exception.RepositoryCheckedException;
import org.lamsfoundation.lams.integration.ExtCourseClassMap;
@@ -70,7 +70,7 @@
* pages
*/
public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) throws IOException, UserAccessDeniedException, JSONException,
+ HttpServletResponse response) throws IOException, UserAccessDeniedException,
RepositoryCheckedException, UserInfoFetchException, UserInfoValidationException {
initServices();
String consumerKey = request.getParameter(LtiUtils.OAUTH_CONSUMER_KEY);
@@ -120,7 +120,7 @@
* design and start a lesson.
*/
public ActionForward addLesson(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) throws IOException, UserAccessDeniedException, JSONException,
+ HttpServletResponse response) throws IOException, UserAccessDeniedException,
RepositoryCheckedException, UserInfoFetchException, UserInfoValidationException {
initServices();
Integer userId = getUser().getUserID();
@@ -156,7 +156,7 @@
* Starts a lesson. Then prompts to learnerMonitor page.
*/
public ActionForward startLesson(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) throws IOException, UserAccessDeniedException, JSONException,
+ HttpServletResponse response) throws IOException, UserAccessDeniedException,
RepositoryCheckedException, UserInfoValidationException, UserInfoFetchException {
initServices();
Integer userId = getUser().getUserID();
@@ -211,7 +211,7 @@
* Once lesson was created, start showing learnerMonitor page to everybody regardless of his role.
*/
public ActionForward learnerMonitor(ActionMapping mapping, ActionForm form, HttpServletRequest request,
- HttpServletResponse response) throws IOException, UserAccessDeniedException, JSONException,
+ HttpServletResponse response) throws IOException, UserAccessDeniedException,
RepositoryCheckedException, UserInfoValidationException, UserInfoFetchException {
initServices();
Integer userId = getUser().getUserID();
Index: lams_central/src/java/org/lamsfoundation/lams/web/planner/PedagogicalPlannerAction.java
===================================================================
diff -u -rb67c428939ed96f08f56192d54b8ee55d8ab89d2 -r2c03060b238558d183472f0066ba003c76d00fd0
--- lams_central/src/java/org/lamsfoundation/lams/web/planner/PedagogicalPlannerAction.java (.../PedagogicalPlannerAction.java) (revision b67c428939ed96f08f56192d54b8ee55d8ab89d2)
+++ lams_central/src/java/org/lamsfoundation/lams/web/planner/PedagogicalPlannerAction.java (.../PedagogicalPlannerAction.java) (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -33,9 +33,7 @@
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.Iterator;
-import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@@ -51,24 +49,6 @@
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
-import org.apache.lucene.analysis.Analyzer;
-import org.apache.lucene.analysis.standard.StandardAnalyzer;
-import org.apache.lucene.document.Document;
-import org.apache.lucene.document.Field;
-import org.apache.lucene.document.StringField;
-import org.apache.lucene.document.TextField;
-import org.apache.lucene.index.CorruptIndexException;
-import org.apache.lucene.index.DirectoryReader;
-import org.apache.lucene.index.IndexWriter;
-import org.apache.lucene.index.IndexWriterConfig;
-import org.apache.lucene.index.IndexWriterConfig.OpenMode;
-import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
-import org.apache.lucene.queryparser.classic.ParseException;
-import org.apache.lucene.search.IndexSearcher;
-import org.apache.lucene.search.Query;
-import org.apache.lucene.search.ScoreDoc;
-import org.apache.lucene.search.TopDocs;
-import org.apache.lucene.store.RAMDirectory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
@@ -124,24 +104,13 @@
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.thoughtworks.xstream.XStream;
-import com.thoughtworks.xstream.converters.reflection.SunUnsafeReflectionProvider;
+import com.thoughtworks.xstream.io.xml.StaxDriver;
import com.thoughtworks.xstream.security.AnyTypePermission;
/**
* Action managing Pedagogical Planner base page and non-tool activities.
*
* @author Marcin Cieslak
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
- *
*/
public class PedagogicalPlannerAction extends LamsDispatchAction {
private static Logger log = Logger.getLogger(PedagogicalPlannerAction.class);
@@ -155,9 +124,6 @@
private static PedagogicalPlannerDAO pedagogicalPlannerDAO;
private static ActivityDAO activityDAO;
- private static final RAMDirectory luceneDir = new RAMDirectory();
- private static final Analyzer luceneAnalyzer = new StandardAnalyzer();
-
private static final String FILE_EXTENSION_ZIP = ".zip";
private static final String FILE_EXTENSION_LAS = ".las";
@@ -354,7 +320,7 @@
throws ServletException {
ActionMessages errors = new ActionMessages();
- List activities = new ArrayList();
+ List activities = new ArrayList<>();
// Create DTOs that hold all the necessary information of the activities
Activity activity = learningDesign.getFirstActivity();
@@ -752,48 +718,13 @@
Boolean edit = WebUtil.readBooleanParam(request, CentralConstants.PARAM_EDIT, false);
edit &= canEdit;
- // Fill the DTO
- PedagogicalPlannerSequenceNodeDTO dto = null;
- if (filterText != null) {
- try {
- // Filtering = display node and all the subnodes that were found in the search (not the immediate
- // children of the node)
- Set filteredNodeUids = filterSubnodes(node, filterText);
- if (filteredNodeUids != null) {
- request.setAttribute(CentralConstants.PARAM_FILTER_TEXT, filterText);
-
- Set filteredNodes = new LinkedHashSet(
- filteredNodeUids.size());
- for (Long filteredUid : filteredNodeUids) {
- PedagogicalPlannerSequenceNode subnode = getPedagogicalPlannerDAO().getByUid(filteredUid);
- filteredNodes.add(subnode);
- }
-
- dto = new PedagogicalPlannerSequenceNodeDTO(node, filteredNodes, isSysAdmin,
- getPedagogicalPlannerDAO());
- for (PedagogicalPlannerSequenceNodeDTO subnodeDTO : dto.getSubnodes()) {
- List titlePath = getPedagogicalPlannerDAO().getTitlePath(subnodeDTO.getUid());
- subnodeDTO.setTitlePath(titlePath);
- }
- }
- } catch (Exception e) {
- PedagogicalPlannerAction.log.error(e, e);
- ActionMessages errors = new ActionMessages();
- errors.add(ActionMessages.GLOBAL_MESSAGE,
- new ActionMessage(PedagogicalPlannerAction.ERROR_KEY_FILTER_PARSE));
- saveErrors(request, errors);
- }
+ // No filtering or something went wrong in filtering
+ PedagogicalPlannerSequenceNodeDTO dto = new PedagogicalPlannerSequenceNodeDTO(node, node.getSubnodes(),
+ isSysAdmin, getPedagogicalPlannerDAO());
+ if (nodeUid == null) {
+ dto.setRecentlyModifiedNodes(getRecentlyModifiedLearnindDesignsAsNodes());
}
- if (dto == null) {
- // No filtering or something went wrong in filtering
- dto = new PedagogicalPlannerSequenceNodeDTO(node, node.getSubnodes(), isSysAdmin,
- getPedagogicalPlannerDAO());
- if (nodeUid == null) {
- dto.setRecentlyModifiedNodes(getRecentlyModifiedLearnindDesignsAsNodes());
- }
- }
-
// Additional DTO parameters
List titlePath = getPedagogicalPlannerDAO().getTitlePath(nodeUid);
Boolean createSubnode = WebUtil.readBooleanParam(request, CentralConstants.PARAM_CREATE_SUBNODE, false);
@@ -1181,7 +1112,7 @@
PedagogicalPlannerSequenceNode node = getPedagogicalPlannerDAO().getByUid(nodeUid);
// exporting XML
- XStream designXml = new XStream(new SunUnsafeReflectionProvider());
+ XStream designXml = new XStream(new StaxDriver());
designXml.addPermission(AnyTypePermission.ANY);
// do not serialize node's owner
designXml.omitField(PedagogicalPlannerSequenceNode.class, "user");
@@ -1306,10 +1237,10 @@
@SuppressWarnings("unchecked")
private LearningDesign importLearningDesign(File sourceFile, ActionMessages errors) throws ServletException {
User user = getUser();
- List toolsErrorMsgs = new ArrayList();
+ List toolsErrorMsgs = new ArrayList<>();
Long learningDesignID = null;
LearningDesign learningDesign = null;
- List learningDesignErrorMsgs = new ArrayList();
+ List learningDesignErrorMsgs = new ArrayList<>();
Integer workspaceFolderId = null;
@@ -1366,7 +1297,7 @@
WorkspaceFolder parentFolder = getUserManagementService().getRootOrganisation().getNormalFolder();
Integer workspaceFolderType = WorkspaceFolder.PUBLIC_SEQUENCES;
- Map properties = new HashMap();
+ Map properties = new HashMap<>();
properties.put("name", name);
properties.put("parentWorkspaceFolder.workspaceFolderId", parentFolder.getWorkspaceFolderId());
properties.put("workspaceFolderType", workspaceFolderType);
@@ -1419,7 +1350,7 @@
}
} else {
- List toolsErrorMsgs = new ArrayList();
+ List toolsErrorMsgs = new ArrayList<>();
String exportedLdFilePath = getExportService().exportLearningDesign(node.getLearningDesignId(),
toolsErrorMsgs);
if (!toolsErrorMsgs.isEmpty()) {
@@ -1477,100 +1408,6 @@
}
}
- /**
- * Finds all node's descendants matching the query. Results can be not only the subnodes of the node, but also
- * deeper descendants. This method uses Lucene project for query parsing and searchig.
- *
- * @param node
- * @param filterText
- * @return set of nodes' uids
- * @throws ParseException
- * @throws CorruptIndexException
- * @throws IOException
- */
- private Set filterSubnodes(PedagogicalPlannerSequenceNode node, String filterText)
- throws ParseException, CorruptIndexException, IOException {
- Set matchingSubnodeUids = new LinkedHashSet();
- if (!StringUtils.isEmpty(filterText)) {
-
- Set docs = extractSubnodeDocuments(node);
- if (!docs.isEmpty()) {
- // Searching is performed in title, brief description and full description of the node.
- MultiFieldQueryParser queryParser = new MultiFieldQueryParser(
- new String[] { PedagogicalPlannerAction.FIELD_NAME_TITLE,
- PedagogicalPlannerAction.FIELD_NAME_FULL_DESCRIPTION,
- PedagogicalPlannerAction.FIELD_NAME_BRIEF_DESCRIPTION },
- PedagogicalPlannerAction.luceneAnalyzer);
-
- Query query = queryParser.parse(filterText);
-
- // build index based on nodes
- IndexWriterConfig config = new IndexWriterConfig(PedagogicalPlannerAction.luceneAnalyzer.getVersion(),
- PedagogicalPlannerAction.luceneAnalyzer);
- config.setOpenMode(OpenMode.CREATE);
- IndexWriter indexWriter = new IndexWriter(PedagogicalPlannerAction.luceneDir, config);
- for (Document doc : docs) {
- indexWriter.addDocument(doc);
- }
- indexWriter.close();
-
- // execute search
- IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(PedagogicalPlannerAction.luceneDir));
- TopDocs topDocs = searcher.search(query, null, docs.size());
-
- for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
- Document doc = searcher.doc(scoreDoc.doc);
- String ancestorUid = doc.get(PedagogicalPlannerAction.FIELD_NAME_ANCESTOR_UID);
- Long uid = new Long(ancestorUid);
- matchingSubnodeUids.add(uid);
- }
- }
- }
- return matchingSubnodeUids;
- }
-
- /**
- * Adds documents made of subnodes' title, descriptions and uid, then descents deeper into descendants.
- *
- * @param node
- * its subnodes will be parsed
- * @return documents made of all of node's descendants
- */
- private Set extractSubnodeDocuments(PedagogicalPlannerSequenceNode node) {
- Set docs = new HashSet();
- if ((node != null) && (node.getSubnodes() != null)) {
- for (PedagogicalPlannerSequenceNode subnode : node.getSubnodes()) {
- Document doc = new Document();
- Field titleField = new TextField(PedagogicalPlannerAction.FIELD_NAME_TITLE, subnode.getTitle(),
- Field.Store.NO);
- titleField.setBoost(10);
- doc.add(titleField);
-
- String briefDesc = WebUtil.removeHTMLtags(subnode.getBriefDescription());
- if (briefDesc != null) {
- Field briefDescField = new TextField(PedagogicalPlannerAction.FIELD_NAME_BRIEF_DESCRIPTION,
- briefDesc, Field.Store.NO);
- doc.add(briefDescField);
- }
- String fullDesc = WebUtil.removeHTMLtags(subnode.getFullDescription());
- if (fullDesc != null) {
- Field fullDescField = new TextField(PedagogicalPlannerAction.FIELD_NAME_FULL_DESCRIPTION, fullDesc,
- Field.Store.NO);
- doc.add(fullDescField);
- }
-
- Field uidField = new StringField(PedagogicalPlannerAction.FIELD_NAME_ANCESTOR_UID,
- subnode.getUid().toString(), Field.Store.YES);
- doc.add(uidField);
- docs.add(doc);
-
- Set subnodeDocs = extractSubnodeDocuments(subnode);
- docs.addAll(subnodeDocs);
- }
- }
- return docs;
- }
-
/*----------------------- GROUPING METHODS -------------------------*/
/**
@@ -1638,7 +1475,7 @@
User user = getUser();
// the list is sorted most-recently-edited-on-top (so by the timestamp descending)
Set recentLDs = user.getRecentlyModifiedLearningDesigns();
- List recentNodes = new LinkedList();
+ List recentNodes = new LinkedList<>();
// create "dummy", almost empty nodes
for (Long learningDesignId : recentLDs) {
LearningDesign learningDesign = getAuthoringService().getLearningDesign(learningDesignId);
@@ -1718,7 +1555,7 @@
if (!StringUtils.isEmpty(activityMetadataString)) {
String[] activityMetadataEntries = activityMetadataString.split("&");
// creata a map of metadata objects, because we are filling them multiple times during this iteration
- Map activitiesMetadata = new TreeMap();
+ Map activitiesMetadata = new TreeMap<>();
for (String activityMetadataEntry : activityMetadataEntries) {
String[] keyAndValue = activityMetadataEntry.split("=");
String[] keyParts = keyAndValue[0].split("\\.");
@@ -1790,7 +1627,7 @@
HttpServletResponse response) throws IOException, ServletException {
Long learningDesignId = WebUtil.readLongParam(request, CentralConstants.PARAM_LEARNING_DESIGN_ID);
- List toolsErrorMsgs = new ArrayList();
+ List toolsErrorMsgs = new ArrayList<>();
ActionMessages errors = new ActionMessages();
String zipFilePath = null;
boolean valid = false;
@@ -1854,7 +1691,7 @@
// list existing users (inherited role from parent nodes)
Set allInheritedUsers = getPedagogicalPlannerDAO().getInheritedNodeUsers(nodeUid, Role.ROLE_SYSADMIN);
- ArrayList filteredInheritedUsers = new ArrayList();
+ ArrayList filteredInheritedUsers = new ArrayList<>();
for (Object o : allInheritedUsers) {
User u = (User) o;
// filter existing users of the actual node
@@ -1865,7 +1702,7 @@
}
// filter existing users from list of potential users
- ArrayList potentialUsers = new ArrayList();
+ ArrayList potentialUsers = new ArrayList<>();
for (Object o : potentialUsersVector) {
User u = (User) o;
if (existingUsers.contains(u) || allInheritedUsers.contains(u)) {
Index: lams_central/src/java/org/lamsfoundation/lams/workspace/service/IWorkspaceManagementService.java
===================================================================
diff -u -rb67c428939ed96f08f56192d54b8ee55d8ab89d2 -r2c03060b238558d183472f0066ba003c76d00fd0
--- lams_central/src/java/org/lamsfoundation/lams/workspace/service/IWorkspaceManagementService.java (.../IWorkspaceManagementService.java) (revision b67c428939ed96f08f56192d54b8ee55d8ab89d2)
+++ lams_central/src/java/org/lamsfoundation/lams/workspace/service/IWorkspaceManagementService.java (.../IWorkspaceManagementService.java) (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -26,7 +26,7 @@
import java.io.IOException;
import java.util.Vector;
-import org.apache.tomcat.util.json.JSONException;
+
import org.lamsfoundation.lams.contentrepository.exception.RepositoryCheckedException;
import org.lamsfoundation.lams.learningdesign.exception.LearningDesignException;
import org.lamsfoundation.lams.usermanagement.User;
@@ -128,7 +128,7 @@
* learning designs and subfolders of the given folder. Sample output:
*/
String getFolderContentsJSON(Integer folderID, Integer userID, boolean allowInvalidDesigns)
- throws JSONException, IOException, UserAccessDeniedException, RepositoryCheckedException;
+ throws IOException, UserAccessDeniedException, RepositoryCheckedException;
/**
* Returns Folder Contents in JSON format, restricted by designType (used for Integrations) If folderID == null,
@@ -137,7 +137,7 @@
* output:
*/
String getFolderContentsJSON(Integer folderID, Integer userID, boolean allowInvalidDesigns, String designType)
- throws JSONException, IOException, UserAccessDeniedException, RepositoryCheckedException;
+ throws IOException, UserAccessDeniedException, RepositoryCheckedException;
/**
* Returns a section of the learning designs in the root of the user's personal folder. Returns the data in in JSON
@@ -148,7 +148,7 @@
* "name":"TBL_BBBBB","date":"2015-07-13 10:07:41.0"}]}
*/
public String getPagedLearningDesignsJSON(Integer userID, boolean allowInvalidDesigns, String searchString,
- int page, int size, String sortName, String sortDate) throws JSONException, IOException;
+ int page, int size, String sortName, String sortDate) throws IOException;
/**
* This method creates a new folder under the given parentFolder inside the user's default workspace.
Index: lams_central/src/java/org/lamsfoundation/lams/workspace/service/WorkspaceManagementService.java
===================================================================
diff -u -rb67c428939ed96f08f56192d54b8ee55d8ab89d2 -r2c03060b238558d183472f0066ba003c76d00fd0
--- lams_central/src/java/org/lamsfoundation/lams/workspace/service/WorkspaceManagementService.java (.../WorkspaceManagementService.java) (revision b67c428939ed96f08f56192d54b8ee55d8ab89d2)
+++ lams_central/src/java/org/lamsfoundation/lams/workspace/service/WorkspaceManagementService.java (.../WorkspaceManagementService.java) (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -34,9 +34,6 @@
import org.apache.commons.lang.StringEscapeUtils;
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.authoring.service.IAuthoringService;
import org.lamsfoundation.lams.contentrepository.exception.RepositoryCheckedException;
import org.lamsfoundation.lams.contentrepository.service.IRepositoryService;
@@ -55,11 +52,16 @@
import org.lamsfoundation.lams.usermanagement.exception.UserException;
import org.lamsfoundation.lams.usermanagement.exception.WorkspaceFolderException;
import org.lamsfoundation.lams.usermanagement.service.IUserManagementService;
+import org.lamsfoundation.lams.util.JsonUtil;
import org.lamsfoundation.lams.util.MessageService;
import org.lamsfoundation.lams.workspace.WorkspaceFolderContent;
import org.lamsfoundation.lams.workspace.dto.FolderContentDTO;
import org.lamsfoundation.lams.workspace.web.WorkspaceAction;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
/**
* @author Manpreet Minhas
*/
@@ -279,7 +281,7 @@
private Vector getFolderContentsInternal(User user, WorkspaceFolder workspaceFolder, Integer mode,
String methodName, WorkspaceFolder skipFolder)
throws UserAccessDeniedException, RepositoryCheckedException {
- Vector contentDTO = new Vector();
+ Vector contentDTO = new Vector<>();
if (user != null) {
Integer permissions = getPermissions(workspaceFolder, user);
if (permissions != WorkspaceFolder.NO_ACCESS) {
@@ -334,22 +336,21 @@
@Override
public String getFolderContentsJSON(Integer folderID, Integer userID, boolean allowInvalidDesigns)
- throws JSONException, IOException, UserAccessDeniedException, RepositoryCheckedException {
+ throws IOException, UserAccessDeniedException, RepositoryCheckedException {
return getFolderContentsJSON(folderID, userID, allowInvalidDesigns, false, null);
}
@Override
public String getFolderContentsJSON(Integer folderID, Integer userID, boolean allowInvalidDesigns,
- String designType)
- throws JSONException, IOException, UserAccessDeniedException, RepositoryCheckedException {
+ String designType) throws IOException, UserAccessDeniedException, RepositoryCheckedException {
return getFolderContentsJSON(folderID, userID, allowInvalidDesigns, false, designType);
}
public String getFolderContentsJSON(Integer folderID, Integer userID, boolean allowInvalidDesigns,
boolean designsOnly, String designType)
- throws JSONException, IOException, UserAccessDeniedException, RepositoryCheckedException {
- JSONObject result = new JSONObject();
+ throws IOException, UserAccessDeniedException, RepositoryCheckedException {
+ ObjectNode result = JsonNodeFactory.instance.objectNode();
Vector folderContents = null;
// folderID == null: get all user accessible folders
@@ -359,7 +360,7 @@
FolderContentDTO userFolder = getUserWorkspaceFolder(userID);
if (folderID == null) {
- folderContents = new Vector(3);
+ folderContents = new Vector<>(3);
if (userFolder != null) {
folderContents.add(userFolder);
@@ -407,15 +408,15 @@
for (FolderContentDTO folderContent : folderContents) {
String contentType = folderContent.getResourceType();
if (FolderContentDTO.FOLDER.equals(contentType) && !designsOnly) {
- JSONObject subfolderJSON = new JSONObject();
+ ObjectNode subfolderJSON = JsonNodeFactory.instance.objectNode();
subfolderJSON.put("name", folderContent.getName() == null ? "" : folderContent.getName());
subfolderJSON.put("isRunSequencesFolder",
WorkspaceFolder.RUN_SEQUENCES.equals(folderContent.getResourceTypeID() == null ? null
: folderContent.getResourceTypeID().intValue()));
subfolderJSON.put("folderID", folderContent.getResourceID().intValue());
subfolderJSON.put("canModify", WorkspaceFolder.OWNER_ACCESS.equals(folderContent.getPermissionCode())
|| ((user != null) && isSysAuthorAdmin(user)));
- result.append("folders", subfolderJSON);
+ result.withArray("folders").add(subfolderJSON);
} else if (FolderContentDTO.DESIGN.equals(contentType)) {
if (folderContent.getDesignType() == null) {
folderContent.setDesignType(WorkspaceManagementService.DEFAULT_DESIGN_TYPE);
@@ -427,15 +428,15 @@
? folderContent.getDesignType().equals(WorkspaceManagementService.DEFAULT_DESIGN_TYPE)
: (designType.equals(WorkspaceManagementService.ALL_DESIGN_TYPES)
|| designType.equals(folderContent.getDesignType()))) {
- JSONObject learningDesignJSON = new JSONObject();
+ ObjectNode learningDesignJSON = JsonNodeFactory.instance.objectNode();
learningDesignJSON.put("name", folderContent.getName() == null ? "" : folderContent.getName());
learningDesignJSON.put("learningDesignId", folderContent.getResourceID());
- learningDesignJSON.putOpt("type", folderContent.getDesignType());
- learningDesignJSON.put("date", folderContent.getLastModifiedDateTime());
+ JsonUtil.putOpt(learningDesignJSON, "type", folderContent.getDesignType());
+ learningDesignJSON.put("date", folderContent.getLastModifiedDateTime().toString());
learningDesignJSON.put("canModify",
WorkspaceFolder.OWNER_ACCESS.equals(folderContent.getPermissionCode())
|| ((user != null) && isSysAuthorAdmin(user)));
- result.append("learningDesigns", learningDesignJSON);
+ result.withArray("learningDesigns").add(learningDesignJSON);
}
} else {
if (log.isDebugEnabled()) {
@@ -449,11 +450,11 @@
@Override
public String getPagedLearningDesignsJSON(Integer userID, boolean allowInvalidDesigns, String searchString,
- int page, int size, String sortName, String sortDate) throws JSONException, IOException {
-
- JSONArray result = new JSONArray();
+ int page, int size, String sortName, String sortDate) throws IOException {
+ ArrayNode resultJSON = JsonNodeFactory.instance.arrayNode();
Pattern searchPattern = searchString != null
- ? Pattern.compile(Pattern.quote(searchString), Pattern.CASE_INSENSITIVE) : null;
+ ? Pattern.compile(Pattern.quote(searchString), Pattern.CASE_INSENSITIVE)
+ : null;
FolderContentDTO userFolder = getUserWorkspaceFolder(userID);
long numDesigns = 0;
@@ -481,27 +482,27 @@
while (iterator.hasNext()) {
LearningDesign design = (LearningDesign) iterator.next();
if ((searchPattern == null) || (searchPattern.matcher(design.getTitle()).find())) {
- JSONObject learningDesignJSON = new JSONObject();
+ ObjectNode learningDesignJSON = JsonNodeFactory.instance.objectNode();
learningDesignJSON.put("name", StringEscapeUtils.escapeHtml(design.getTitle()));
learningDesignJSON.put("learningDesignId", design.getLearningDesignId());
- learningDesignJSON.putOpt("type", design.getDesignType() != null ? design.getDesignType()
+ learningDesignJSON.put("type", design.getDesignType() != null ? design.getDesignType()
: WorkspaceManagementService.DEFAULT_DESIGN_TYPE);
- learningDesignJSON.put("date", design.getLastModifiedDateTime());
- result.put(learningDesignJSON);
+ learningDesignJSON.put("date", design.getLastModifiedDateTime().toString());
+ resultJSON.add(learningDesignJSON);
}
}
// what is the total number (so the pager knows whether to allow paging)
// if we did a search, then no paging just return the whole lot.
// otherwise need the whole count from the db.
- numDesigns = searchPattern != null ? result.length()
+ numDesigns = searchPattern != null ? resultJSON.size()
: learningDesignDAO.countAllLearningDesigns(folderId, !allowInvalidDesigns);
}
- JSONObject completeResult = new JSONObject();
+ ObjectNode completeResult = JsonNodeFactory.instance.objectNode();
completeResult.put("total_rows", numDesigns);
- if (result.length() > 0) {
- completeResult.put("rows", result);
+ if (resultJSON.size() > 0) {
+ completeResult.set("rows", resultJSON);
}
return completeResult.toString();
}
@@ -837,7 +838,7 @@
*/
@Override
public Vector getAccessibleOrganisationWorkspaceFolders(User user) throws IOException {
- Vector folders = new Vector();
+ Vector folders = new Vector<>();
if (user != null) {
// Get a list of organisations of which the given user is a member
Index: lams_common/src/java/org/lamsfoundation/lams/integration/service/IntegrationService.java
===================================================================
diff -u -r5bf2d3b201efb46864182d72901e497d0acb253f -r2c03060b238558d183472f0066ba003c76d00fd0
--- lams_common/src/java/org/lamsfoundation/lams/integration/service/IntegrationService.java (.../IntegrationService.java) (revision 5bf2d3b201efb46864182d72901e497d0acb253f)
+++ lams_common/src/java/org/lamsfoundation/lams/integration/service/IntegrationService.java (.../IntegrationService.java) (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -43,8 +43,6 @@
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
-import org.apache.tomcat.util.json.JSONArray;
-import org.apache.tomcat.util.json.JSONObject;
import org.imsglobal.pox.IMSPOXRequest;
import org.lamsfoundation.lams.gradebook.GradebookUserLesson;
import org.lamsfoundation.lams.gradebook.service.IGradebookService;
@@ -73,10 +71,14 @@
import org.lamsfoundation.lams.usermanagement.service.IUserManagementService;
import org.lamsfoundation.lams.util.CSVUtil;
import org.lamsfoundation.lams.util.HashUtil;
+import org.lamsfoundation.lams.util.JsonUtil;
import org.lamsfoundation.lams.util.LanguageUtil;
import org.lamsfoundation.lams.util.ValidationUtil;
import org.lamsfoundation.lams.util.WebUtil;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+
import oauth.signpost.exception.OAuthException;
/**
@@ -772,25 +774,22 @@
BufferedReader isReader = new BufferedReader(new InputStreamReader(is));
String str = isReader.readLine();
- JSONArray jsonGroups = new JSONArray(str);
+ ArrayNode jsonGroups = JsonUtil.readArray(str);
List extGroups = new ArrayList<>();
- for (int i = 0; i < jsonGroups.length(); i++) {
- JSONObject jsonGroup = jsonGroups.getJSONObject(i);
+ for (JsonNode jsonGroup : jsonGroups) {
ExtGroupDTO group = new ExtGroupDTO();
- group.setGroupName(jsonGroup.getString("groupName"));
- group.setGroupId(jsonGroup.getString("groupId"));
+ group.setGroupName(JsonUtil.optString(jsonGroup, "groupName"));
+ group.setGroupId(JsonUtil.optString(jsonGroup, "groupId"));
extGroups.add(group);
// in case group info is also requested - provide selected groups' ids
if (extGroupIds != null && extGroupIds.length > 0) {
ArrayList users = new ArrayList<>();
- JSONArray jsonUsers = jsonGroup.getJSONArray("users");
- for (int j = 0; j < jsonUsers.length(); j++) {
- JSONObject jsonUser = jsonUsers.getJSONObject(j);
+ ArrayNode jsonUsers = JsonUtil.optArray(jsonGroup, "users");
+ for (JsonNode jsonUser : jsonUsers) {
+ String extUsername = JsonUtil.optString(jsonUser, "userName");
- String extUsername = jsonUser.getString("userName");
-
ExtUserUseridMap extUserUseridMap = getExistingExtUserUseridMap(extServer, extUsername);
//create extUserUseridMap if it's not available
@@ -800,7 +799,7 @@
// language>,
String[] userData = new String[14];
for (int k = 1; k <= 14; k++) {
- String userProperty = jsonUser.getString("" + k);
+ String userProperty = JsonUtil.optString(jsonUser, "" + k);
userData[k - 1] = userProperty;
}
String salt = HashUtil.salt();
@@ -824,7 +823,7 @@
group.setUsers(users);
} else {
- group.setNumberUsers(jsonGroup.getInt("groupSize"));
+ group.setNumberUsers(JsonUtil.optInt(jsonGroup, "groupSize"));
}
}
Index: lams_common/src/java/org/lamsfoundation/lams/learningdesign/service/ExportToolContentService.java
===================================================================
diff -u -r2623eb7399f1ea9633c776630f379fa48a21b7e9 -r2c03060b238558d183472f0066ba003c76d00fd0
--- lams_common/src/java/org/lamsfoundation/lams/learningdesign/service/ExportToolContentService.java (.../ExportToolContentService.java) (revision 2623eb7399f1ea9633c776630f379fa48a21b7e9)
+++ lams_common/src/java/org/lamsfoundation/lams/learningdesign/service/ExportToolContentService.java (.../ExportToolContentService.java) (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -141,9 +141,10 @@
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.reflection.ReflectionConverter;
-import com.thoughtworks.xstream.converters.reflection.SunUnsafeReflectionProvider;
+
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
+import com.thoughtworks.xstream.io.xml.StaxDriver;
import com.thoughtworks.xstream.security.AnyTypePermission;
/**
@@ -477,7 +478,7 @@
}
// exporting XML
- XStream designXml = new XStream(new SunUnsafeReflectionProvider());
+ XStream designXml = new XStream(new StaxDriver());
designXml.addPermission(AnyTypePermission.ANY);
designXml.toXML(ldDto, ldFile);
ldFile.close();
@@ -548,7 +549,7 @@
Writer toolFile = new OutputStreamWriter(new FileOutputStream(toolFileName), "UTF-8");
// serialize tool xml into local file.
- XStream toolXml = new XStream(new SunUnsafeReflectionProvider());
+ XStream toolXml = new XStream(new StaxDriver());
toolXml.addPermission(AnyTypePermission.ANY);
FileConverter fileConverter = null;
if (!fileHandleClassList.isEmpty()) {
@@ -896,7 +897,7 @@
String toVersion) throws ImportToolContentException {
Object toolPOJO = null;
// change xml to Tool POJO
- XStream toolXml = new XStream(new SunUnsafeReflectionProvider());
+ XStream toolXml = new XStream(new StaxDriver());
toolXml.addPermission(AnyTypePermission.ANY);
FileConverter fileConverter = null;
if (!fileHandleClassList.isEmpty()) {
Index: lams_learning/web/WEB-INF/web.xml
===================================================================
diff -u -r34815c1edfbbd510266420e5cfaf4baf290e9a1e -r2c03060b238558d183472f0066ba003c76d00fd0
--- lams_learning/web/WEB-INF/web.xml (.../web.xml) (revision 34815c1edfbbd510266420e5cfaf4baf290e9a1e)
+++ lams_learning/web/WEB-INF/web.xml (.../web.xml) (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -34,7 +34,7 @@
HibernateFilter
- org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
+ org.springframework.orm.hibernate5.support.OpenSessionInViewFilter
sessionFactoryBeanName
coreSessionFactory
Index: lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java
===================================================================
diff -u -re34e0b7a8ed604692164d998b9a7d6944adfc487 -r2c03060b238558d183472f0066ba003c76d00fd0
--- lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java (.../AssessmentServiceImpl.java) (revision e34e0b7a8ed604692164d998b9a7d6944adfc487)
+++ lams_tool_assessment/src/java/org/lamsfoundation/lams/tool/assessment/service/AssessmentServiceImpl.java (.../AssessmentServiceImpl.java) (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -23,6 +23,7 @@
package org.lamsfoundation.lams.tool.assessment.service;
+import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.util.ArrayList;
@@ -48,9 +49,6 @@
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.IndexedColors;
-import org.apache.tomcat.util.json.JSONArray;
-import org.apache.tomcat.util.json.JSONException;
-import org.apache.tomcat.util.json.JSONObject;
import org.lamsfoundation.lams.events.IEventNotificationService;
import org.lamsfoundation.lams.gradebook.service.IGradebookService;
import org.lamsfoundation.lams.learning.service.ILearnerService;
@@ -112,6 +110,10 @@
import org.lamsfoundation.lams.util.NumberUtil;
import org.lamsfoundation.lams.util.audit.IAuditService;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
/**
* @author Andrey Balan
*/
@@ -428,7 +430,7 @@
@Override
public void setAttemptStarted(Assessment assessment, AssessmentUser assessmentUser, Long toolSessionId) {
Set questions = assessment.getQuestions();
-
+
AssessmentResult lastResult = getLastAssessmentResult(assessment.getUid(), assessmentUser.getUserId());
if (lastResult != null) {
@@ -457,7 +459,7 @@
assessmentResultDao.saveObject(lastResult);
return;
- // mark previous attempt as being not the latest any longer
+ // mark previous attempt as being not the latest any longer
} else {
lastResult.setLatest(false);
assessmentResultDao.saveObject(lastResult);
@@ -528,7 +530,8 @@
for (QuestionDTO questionDto : questionsForOnePage) {
// in case single MarkHedging question needs to be stored -- search for that question
- if ((singleMarkHedgingQuestionUid != null) && !questionDto.getUid().equals(singleMarkHedgingQuestionUid)) {
+ if ((singleMarkHedgingQuestionUid != null)
+ && !questionDto.getUid().equals(singleMarkHedgingQuestionUid)) {
continue;
}
@@ -585,24 +588,24 @@
* @param isAutosave
* in case of autosave there is no need to calculate marks
* @return grade that user scored by answering that question
- * @throws NoSuchMethodException
- * @throws InvocationTargetException
- * @throws IllegalAccessException
+ * @throws NoSuchMethodException
+ * @throws InvocationTargetException
+ * @throws IllegalAccessException
*/
- private float storeUserAnswer(AssessmentResult assessmentResult, QuestionDTO questionDto, boolean isAutosave) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
+ private float storeUserAnswer(AssessmentResult assessmentResult, QuestionDTO questionDto, boolean isAutosave)
+ throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Assessment assessment = assessmentResult.getAssessment();
-
+
AssessmentQuestionResult questionResult = null;
// get questionResult from DB instance of AssessmentResult
for (AssessmentQuestionResult questionResultIter : assessmentResult.getQuestionResults()) {
if (questionDto.getUid().equals(questionResultIter.getAssessmentQuestion().getUid())) {
questionResult = questionResultIter;
}
}
-
- //if teacher edited content in monitor (modified question) it led to removal if autosaved questionResult
- if (assessment.isContentModifiedInMonitor(assessmentResult.getStartDate())
- && questionResult == null) {
+
+ //if teacher edited content in monitor (modified question) it led to removal if autosaved questionResult
+ if (assessment.isContentModifiedInMonitor(assessmentResult.getStartDate()) && questionResult == null) {
//update questionDto
AssessmentQuestion modifiedQuestion = assessmentQuestionDao.getByUid(questionDto.getUid());
QuestionDTO updatedQuestionDto = modifiedQuestion.getQuestionDTO();
@@ -694,7 +697,8 @@
java.util.regex.Pattern.CASE_INSENSITIVE | java.util.regex.Pattern.UNICODE_CASE);
}
boolean isAnswerMatchedCurrentOption = (questionDto.getAnswerString() != null)
- ? pattern.matcher(questionDto.getAnswerString().trim()).matches() : false;
+ ? pattern.matcher(questionDto.getAnswerString().trim()).matches()
+ : false;
if (isAnswerMatchedCurrentOption) {
mark = optionDto.getGrade() * maxMark;
@@ -710,7 +714,8 @@
boolean isAnswerMatchedCurrentOption = false;
try {
float answerFloat = Float.valueOf(questionDto.getAnswerString());
- isAnswerMatchedCurrentOption = ((answerFloat >= (optionDto.getOptionFloat() - optionDto.getAcceptedError()))
+ isAnswerMatchedCurrentOption = ((answerFloat >= (optionDto.getOptionFloat()
+ - optionDto.getAcceptedError()))
&& (answerFloat <= (optionDto.getOptionFloat() + optionDto.getAcceptedError())));
} catch (Exception e) {
}
@@ -728,7 +733,8 @@
answerFloat = answerFloat / unit.getMultiplier();
isAnswerMatchedCurrentOption = ((answerFloat >= (optionDto.getOptionFloat()
- optionDto.getAcceptedError()))
- && (answerFloat <= (optionDto.getOptionFloat() + optionDto.getAcceptedError())));
+ && (answerFloat <= (optionDto.getOptionFloat()
+ + optionDto.getAcceptedError())));
if (isAnswerMatchedCurrentOption) {
break;
}
@@ -746,15 +752,16 @@
}
} else if (questionDto.getType() == AssessmentConstants.QUESTION_TYPE_TRUE_FALSE) {
- if ((questionDto.getAnswerBoolean() == questionDto.getCorrectAnswer()) && (questionDto.getAnswerString() != null)) {
+ if ((questionDto.getAnswerBoolean() == questionDto.getCorrectAnswer())
+ && (questionDto.getAnswerString() != null)) {
mark = maxMark;
}
} else if (questionDto.getType() == AssessmentConstants.QUESTION_TYPE_ORDERING) {
float maxMarkForCorrectAnswer = maxMark / questionDto.getOptionDtos().size();
- TreeSet correctOptionSet = new TreeSet(new SequencableComparator());
+ TreeSet correctOptionSet = new TreeSet<>(new SequencableComparator());
correctOptionSet.addAll(questionDto.getOptionDtos());
- ArrayList correctOptionList = new ArrayList(correctOptionSet);
+ ArrayList correctOptionList = new ArrayList<>(correctOptionSet);
int i = 0;
for (OptionDTO optionDto : questionDto.getOptionDtos()) {
if (optionDto.getUid() == correctOptionList.get(i++).getUid()) {
@@ -923,7 +930,7 @@
@Override
public List getReflectList(Long contentId) {
- List reflectList = new LinkedList();
+ List reflectList = new LinkedList<>();
List sessionList = assessmentSessionDao.getByContentId(contentId);
for (AssessmentSession session : sessionList) {
@@ -974,22 +981,28 @@
@Override
public List getSessionDtos(Long contentId, boolean includeStatistics) {
- List sessionDtos = new ArrayList();
+ List sessionDtos = new ArrayList<>();
List sessionList = assessmentSessionDao.getByContentId(contentId);
for (AssessmentSession session : sessionList) {
Long sessionId = session.getSessionId();
SessionDTO sessionDto = new SessionDTO(sessionId, session.getSessionName());
//for statistics tab
- if ( includeStatistics ) {
+ if (includeStatistics) {
int countUsers = assessmentUserDao.getCountUsersBySession(sessionId, "");
sessionDto.setNumberLearners(countUsers);
Object[] markStats = assessmentUserDao.getStatsMarksBySession(sessionId);
- if ( markStats != null ) {
- sessionDto.setMinMark(markStats[0] != null ? NumberUtil.formatLocalisedNumber((Float)markStats[0], (Locale)null, 2) : "0.00");
- sessionDto.setAvgMark(markStats[1] != null ? NumberUtil.formatLocalisedNumber((Float)markStats[1], (Locale)null, 2) : "0.00");
- sessionDto.setMaxMark(markStats[2] != null ? NumberUtil.formatLocalisedNumber((Float)markStats[2], (Locale)null, 2) : "0.00");
+ if (markStats != null) {
+ sessionDto.setMinMark(markStats[0] != null
+ ? NumberUtil.formatLocalisedNumber((Float) markStats[0], (Locale) null, 2)
+ : "0.00");
+ sessionDto.setAvgMark(markStats[1] != null
+ ? NumberUtil.formatLocalisedNumber((Float) markStats[1], (Locale) null, 2)
+ : "0.00");
+ sessionDto.setMaxMark(markStats[2] != null
+ ? NumberUtil.formatLocalisedNumber((Float) markStats[2], (Locale) null, 2)
+ : "0.00");
}
}
@@ -1003,20 +1016,26 @@
public LeaderResultsDTO getLeaderResultsDTOForLeaders(Long contentId) {
LeaderResultsDTO newDto = new LeaderResultsDTO(contentId);
Object[] markStats = assessmentUserDao.getStatsMarksForLeaders(contentId);
- if ( markStats != null ) {
- newDto.setMinMark(markStats[0] != null ? NumberUtil.formatLocalisedNumber((Float)markStats[0], (Locale)null, 2) : "0.00");
- newDto.setAvgMark(markStats[1] != null ? NumberUtil.formatLocalisedNumber((Float)markStats[1], (Locale)null, 2) : "0.00");
- newDto.setMaxMark(markStats[2] != null ? NumberUtil.formatLocalisedNumber((Float)markStats[2], (Locale)null, 2) : "0.00");
- newDto.setNumberGroupsLeaderFinished((Integer)markStats[3]);
+ if (markStats != null) {
+ newDto.setMinMark(
+ markStats[0] != null ? NumberUtil.formatLocalisedNumber((Float) markStats[0], (Locale) null, 2)
+ : "0.00");
+ newDto.setAvgMark(
+ markStats[1] != null ? NumberUtil.formatLocalisedNumber((Float) markStats[1], (Locale) null, 2)
+ : "0.00");
+ newDto.setMaxMark(
+ markStats[2] != null ? NumberUtil.formatLocalisedNumber((Float) markStats[2], (Locale) null, 2)
+ : "0.00");
+ newDto.setNumberGroupsLeaderFinished((Integer) markStats[3]);
}
return newDto;
}
-
+
@Override
public AssessmentResultDTO getUserMasterDetail(Long sessionId, Long userId) {
AssessmentResultDTO resultDto = new AssessmentResultDTO();
resultDto.setSessionId(sessionId);
-
+
AssessmentResult lastFinishedResult = assessmentResultDao.getLastFinishedAssessmentResultByUser(sessionId,
userId);
if (lastFinishedResult != null) {
@@ -1025,13 +1044,13 @@
Set questionResults = lastFinishedResult.getQuestionResults();
//prepare list of the questions to display in user master detail table, filtering out questions that aren't supposed to be answered
- SortedSet questionResultsToDisplay = new TreeSet(
+ SortedSet questionResultsToDisplay = new TreeSet<>(
new AssessmentQuestionResultComparator());
//in case there is at least one random question - we need to show all questions
if (assessment.hasRandomQuestion()) {
questionResultsToDisplay.addAll(questionResults);
- //otherwise show only questions from the question list
+ //otherwise show only questions from the question list
} else {
for (QuestionReference reference : questionReferences) {
for (AssessmentQuestionResult questionResult : questionResults) {
@@ -1053,7 +1072,7 @@
@Override
public UserSummary getUserSummary(Long contentId, Long userId, Long sessionId) {
Assessment assessment = assessmentDao.getByContentId(contentId);
-
+
UserSummary userSummary = new UserSummary();
AssessmentUser user = assessmentUserDao.getUserByUserIDAndSessionID(userId, sessionId);
userSummary.setUser(user);
@@ -1068,11 +1087,11 @@
if (lastFinishedResult != null) {
userSummary.setLastAttemptGrade(lastFinishedResult.getGrade());
}
-
+
if (!results.isEmpty()) {
//prepare list of the questions to display, filtering out questions that aren't supposed to be answered
- Set questions = new TreeSet();
+ Set questions = new TreeSet<>();
//in case there is at least one random question - we need to show all questions in a drop down select
if (assessment.hasRandomQuestion()) {
questions.addAll(assessment.getQuestions());
@@ -1085,12 +1104,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())) {
@@ -1125,27 +1144,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()) {
@@ -1165,14 +1184,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;
@@ -1221,12 +1240,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) {
@@ -1237,8 +1256,8 @@
ExcelCell[] sessionTitle = new ExcelCell[1];
sessionTitle[0] = new ExcelCell(sessionDTO.getSessionName(), true);
summaryTab.add(sessionTitle);
-
- List userDtos = new ArrayList();
+
+ List userDtos = new ArrayList<>();
// in case of UseSelectLeaderToolOuput - display only one user
if (assessment.isUseSelectLeaderToolOuput()) {
@@ -1264,12 +1283,15 @@
userDtos = getPagedUsersBySession(sessionId, 0, countSessionUsers, "userName", "ASC", "");
}
- ArrayList summaryTabLearnerList = new ArrayList();
-
+ ArrayList summaryTabLearnerList = new ArrayList<>();
+
ExcelCell[] summaryRowTitle = new ExcelCell[3];
- summaryRowTitle[0] = new ExcelCell(getMessage("label.export.user.id"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN);
- summaryRowTitle[1] = new ExcelCell(getMessage("label.monitoring.summary.user.name"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN);
- summaryRowTitle[2] = new ExcelCell(getMessage("label.monitoring.summary.total"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN);
+ summaryRowTitle[0] = new ExcelCell(getMessage("label.export.user.id"), true,
+ ExcelCell.BORDER_STYLE_BOTTOM_THIN);
+ summaryRowTitle[1] = new ExcelCell(getMessage("label.monitoring.summary.user.name"), true,
+ ExcelCell.BORDER_STYLE_BOTTOM_THIN);
+ summaryRowTitle[2] = new ExcelCell(getMessage("label.monitoring.summary.total"), true,
+ ExcelCell.BORDER_STYLE_BOTTOM_THIN);
summaryTabLearnerList.add(summaryRowTitle);
float minGrade = -9999999;
@@ -1284,18 +1306,22 @@
userResultRow[2] = new ExcelCell(grade, false);
summaryTabLearnerList.add(userResultRow);
- if ( grade < minGrade || minGrade == -9999999 )
+ if (grade < minGrade || minGrade == -9999999) {
minGrade = grade;
- if ( grade > maxGrade )
+ }
+ if (grade > maxGrade) {
maxGrade = grade;
+ }
}
- if ( minGrade == -9999999)
+ if (minGrade == -9999999) {
minGrade = 0;
+ }
- LinkedHashMap markSummary = getMarksSummaryForSession(userDtos, minGrade, maxGrade, 10);
+ LinkedHashMap markSummary = getMarksSummaryForSession(userDtos, minGrade, maxGrade,
+ 10);
// work out total marks so we can do percentages. need as float for the correct divisions
int totalNumEntries = 0;
- for ( Map.Entry entry : markSummary.entrySet() ) {
+ for (Map.Entry entry : markSummary.entrySet()) {
totalNumEntries += entry.getValue();
}
@@ -1307,25 +1333,29 @@
summaryTab.add(minMaxRow);
minMaxRow = new ExcelCell[2];
minMaxRow[0] = new ExcelCell(getMessage("label.lowest.mark"), true);
- minMaxRow[1] = new ExcelCell((double)minGrade, false);
+ minMaxRow[1] = new ExcelCell((double) minGrade, false);
summaryTab.add(minMaxRow);
minMaxRow = new ExcelCell[2];
minMaxRow[0] = new ExcelCell(getMessage("label.highest.mark"), true);
- minMaxRow[1] = new ExcelCell((double)maxGrade, false);
+ minMaxRow[1] = new ExcelCell((double) maxGrade, false);
summaryTab.add(minMaxRow);
-
+
summaryTab.add(EMPTY_ROW);
ExcelCell[] binSummaryRow = new ExcelCell[3];
- binSummaryRow[0] = new ExcelCell(getMessage("label.authoring.basic.list.header.mark"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN);
- binSummaryRow[1] = new ExcelCell(getMessage("label.number.learners"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN);
- binSummaryRow[2] = new ExcelCell(getMessage("label.percentage"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN);
+ binSummaryRow[0] = new ExcelCell(getMessage("label.authoring.basic.list.header.mark"), true,
+ ExcelCell.BORDER_STYLE_BOTTOM_THIN);
+ binSummaryRow[1] = new ExcelCell(getMessage("label.number.learners"), true,
+ ExcelCell.BORDER_STYLE_BOTTOM_THIN);
+ binSummaryRow[2] = new ExcelCell(getMessage("label.percentage"), true,
+ ExcelCell.BORDER_STYLE_BOTTOM_THIN);
summaryTab.add(binSummaryRow);
- float totalNumEntriesAsFloat = (float) totalNumEntries;
- for ( Map.Entry entry : markSummary.entrySet() ) {
+ float totalNumEntriesAsFloat = totalNumEntries;
+ for (Map.Entry entry : markSummary.entrySet()) {
binSummaryRow = new ExcelCell[3];
- binSummaryRow[0] = new ExcelCell(entry.getKey(),false);
- binSummaryRow[1] = new ExcelCell(entry.getValue(),false);
- binSummaryRow[2] = new ExcelCell(Math.round(entry.getValue() / totalNumEntriesAsFloat * 100),false);
+ binSummaryRow[0] = new ExcelCell(entry.getKey(), false);
+ binSummaryRow[1] = new ExcelCell(entry.getValue(), false);
+ binSummaryRow[2] = new ExcelCell(Math.round(entry.getValue() / totalNumEntriesAsFloat * 100),
+ false);
summaryTab.add(binSummaryRow);
}
summaryTab.add(EMPTY_ROW);
@@ -1342,7 +1372,7 @@
// ------------------------------------------------------------------
// -------------- Second tab: Question Summary ----------------------
- ArrayList questionSummaryTab = new ArrayList();
+ ArrayList questionSummaryTab = new ArrayList<>();
// Create the question summary
ExcelCell[] summaryTitle = new ExcelCell[1];
@@ -1382,13 +1412,13 @@
ExcelCell.BORDER_STYLE_BOTTOM_THIN);
int questionNumber = 1;
-
+
for (AssessmentQuestion question : questions) {
int colsNum = showUserNames ? 10 : 9;
ExcelCell[] questionTitle = new ExcelCell[1];
- questionTitle[0] = new ExcelCell(getMessage("label.monitoring.question.summary.question") + " "
- + questionNumber++, true);
+ questionTitle[0] = new ExcelCell(
+ getMessage("label.monitoring.question.summary.question") + " " + questionNumber++, true);
questionSummaryTab.add(questionTitle);
// set up the summary table data for the top of the question area.
@@ -1398,16 +1428,16 @@
|| question.getType() == AssessmentConstants.QUESTION_TYPE_TRUE_FALSE;
// For MC, Numeric & Short Answer Key is optionUid, Value is number of answers
// For True/False Key 0 is false and Key 1 is true
- Map summaryOfAnswers = new HashMap();
+ Map summaryOfAnswers = new HashMap<>();
Integer summaryNACount = 0;
Long trueKey = 1L;
Long falseKey = 0L;
if (doSummaryTable) {
questionSummaryTab.add(startSummaryTable(question, summaryOfAnswers, trueKey, falseKey));
}
-
- ArrayList questionSummaryTabTemp = new ArrayList();
+ ArrayList questionSummaryTabTemp = new ArrayList<>();
+
//add question title row
if (question.getType() == AssessmentConstants.QUESTION_TYPE_MARK_HEDGING) {
count = 0;
@@ -1488,9 +1518,10 @@
} else {
userResultRow[count++] = new ExcelCell(
AssessmentEscapeUtils.printResponsesForExcelExport(questionResult), false);
-
- if ( doSummaryTable ) {
- summaryNACount = updateSummaryCounts(question, questionResult, summaryOfAnswers, summaryNACount);
+
+ if (doSummaryTable) {
+ summaryNACount = updateSummaryCounts(question, questionResult, summaryOfAnswers,
+ summaryNACount);
}
}
@@ -1518,10 +1549,11 @@
}
if (doSummaryTable) {
- questionSummaryTab.add(outputSummaryTable(question, summaryOfAnswers, summaryNACount, trueKey, falseKey));
+ questionSummaryTab
+ .add(outputSummaryTable(question, summaryOfAnswers, summaryNACount, trueKey, falseKey));
questionSummaryTab.add(EMPTY_ROW);
}
-
+
// Calculating the averages
ExcelCell[] averageRow;
@@ -1557,7 +1589,7 @@
questionSummaryTab.addAll(questionSummaryTabTemp);
questionSummaryTab.add(averageRow);
questionSummaryTab.add(EMPTY_ROW);
-
+
}
}
@@ -1567,24 +1599,29 @@
// ------------------------------------------------------------------
// -------------- Third tab: User Summary ---------------------------
- ArrayList userSummaryTab = new ArrayList();
+ ArrayList userSummaryTab = new ArrayList<>();
// Create the question summary
ExcelCell[] userSummaryTitle = new ExcelCell[1];
userSummaryTitle[0] = new ExcelCell(getMessage("label.export.user.summary"), true);
userSummaryTab.add(userSummaryTitle);
ExcelCell[] summaryRowTitle = new ExcelCell[5];
- summaryRowTitle[0] = new ExcelCell(getMessage("label.monitoring.question.summary.question"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN);
- summaryRowTitle[1] = new ExcelCell(getMessage("label.authoring.basic.list.header.type"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN);
- summaryRowTitle[2] = new ExcelCell(getMessage("label.authoring.basic.penalty.factor"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN);
- summaryRowTitle[3] = new ExcelCell(getMessage("label.monitoring.question.summary.default.mark"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN);
- summaryRowTitle[4] = new ExcelCell(getMessage("label.monitoring.question.summary.average.mark"), true, ExcelCell.BORDER_STYLE_BOTTOM_THIN);
+ summaryRowTitle[0] = new ExcelCell(getMessage("label.monitoring.question.summary.question"), true,
+ ExcelCell.BORDER_STYLE_BOTTOM_THIN);
+ summaryRowTitle[1] = new ExcelCell(getMessage("label.authoring.basic.list.header.type"), true,
+ ExcelCell.BORDER_STYLE_BOTTOM_THIN);
+ summaryRowTitle[2] = new ExcelCell(getMessage("label.authoring.basic.penalty.factor"), true,
+ ExcelCell.BORDER_STYLE_BOTTOM_THIN);
+ summaryRowTitle[3] = new ExcelCell(getMessage("label.monitoring.question.summary.default.mark"), true,
+ ExcelCell.BORDER_STYLE_BOTTOM_THIN);
+ summaryRowTitle[4] = new ExcelCell(getMessage("label.monitoring.question.summary.average.mark"), true,
+ ExcelCell.BORDER_STYLE_BOTTOM_THIN);
userSummaryTab.add(summaryRowTitle);
Float totalGradesPossible = new Float(0);
Float totalAverage = new Float(0);
if (assessment.getQuestionReferences() != null) {
- Set questionReferences = new TreeSet(new SequencableComparator());
+ Set questionReferences = new TreeSet<>(new SequencableComparator());
questionReferences.addAll(assessment.getQuestionReferences());
int randomQuestionsCount = 1;
@@ -1640,7 +1677,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);
}
@@ -1752,30 +1789,26 @@
summaryTable = new ExcelCell[question.getOptions().size() + 1];
for (AssessmentQuestionOption option : question.getOptions()) {
summaryOfAnswers.put(option.getUid(), 0);
- StringBuilder bldr = new StringBuilder(getMessage("label.authoring.basic.option.answer"))
- .append(" ")
- .append(i + 1)
- .append(" - ");
- if ( question.getType() == AssessmentConstants.QUESTION_TYPE_NUMERICAL ) {
- bldr.append(option.getOptionFloat())
- .append(" +- ")
- .append(option.getAcceptedError());
+ StringBuilder bldr = new StringBuilder(getMessage("label.authoring.basic.option.answer")).append(" ")
+ .append(i + 1).append(" - ");
+ if (question.getType() == AssessmentConstants.QUESTION_TYPE_NUMERICAL) {
+ bldr.append(option.getOptionFloat()).append(" +- ").append(option.getAcceptedError());
} else {
bldr.append(option.getOptionString().replaceAll("\\<.*?\\>", ""));
}
summaryTable[i] = new ExcelCell(bldr.toString(), false);
i++;
}
- if ( question.getType() == AssessmentConstants.QUESTION_TYPE_MULTIPLE_CHOICE ) {
- summaryTable[i++] = new ExcelCell(getMessage("label.not.answered"), false);
+ if (question.getType() == AssessmentConstants.QUESTION_TYPE_MULTIPLE_CHOICE) {
+ summaryTable[i++] = new ExcelCell(getMessage("label.not.answered"), false);
} else {
- summaryTable[i++] = new ExcelCell(getMessage("label.other"), false);
+ summaryTable[i++] = new ExcelCell(getMessage("label.other"), false);
}
} else {
summaryTable = new ExcelCell[3];
summaryTable[0] = new ExcelCell(getMessage("label.authoring.true.false.true"), false);
summaryTable[1] = new ExcelCell(getMessage("label.authoring.true.false.false"), false);
- summaryTable[2] = new ExcelCell(getMessage("label.not.answered"), false);
+ summaryTable[2] = new ExcelCell(getMessage("label.not.answered"), false);
summaryOfAnswers.put(trueKey, 0);
summaryOfAnswers.put(falseKey, 0);
}
@@ -1792,11 +1825,10 @@
if (optionAnswer.getAnswerBoolean()) {
Integer currentCount = summaryOfAnswers.get(optionAnswer.getOptionUid());
if (currentCount == null) {
- log.error("Assessment Export: Unable to count answer in summary, refers to an unexpected option. QuestionResult "
- + questionResult.getUid()
- + " OptionUid "
- + optionAnswer.getOptionUid()
- + " question " + question.getUid());
+ log.error(
+ "Assessment Export: Unable to count answer in summary, refers to an unexpected option. QuestionResult "
+ + questionResult.getUid() + " OptionUid " + optionAnswer.getOptionUid()
+ + " question " + question.getUid());
} else {
summaryOfAnswers.put(optionAnswer.getOptionUid(), currentCount + 1);
foundOption = true;
@@ -1813,12 +1845,10 @@
if (submittedUid != null) {
Integer currentCount = summaryOfAnswers.get(submittedUid);
if (currentCount == null) {
- log.error("Assessment Export: Unable to count answer in summary, refers to an unexpected option. QuestionResult "
- + questionResult.getUid()
- + " submittedOptionUid "
- + submittedUid
- + " question "
- + question.getUid());
+ log.error(
+ "Assessment Export: Unable to count answer in summary, refers to an unexpected option. QuestionResult "
+ + questionResult.getUid() + " submittedOptionUid " + submittedUid + " question "
+ + question.getUid());
} else {
summaryOfAnswers.put(submittedUid, currentCount + 1);
}
@@ -1839,39 +1869,38 @@
private String valueAsPercentage(Integer value, int total) {
Double percentage = (double) value / total * 100;
- return NumberUtil.formatLocalisedNumber(percentage, (Locale)null, 2) + "%";
- }
-
+ return NumberUtil.formatLocalisedNumber(percentage, (Locale) null, 2) + "%";
+ }
+
private ExcelCell[] outputSummaryTable(AssessmentQuestion question, Map summaryOfAnswers,
Integer summaryNACount, Long trueKey, Long falseKey) {
- ExcelCell[] summaryTable = new ExcelCell[summaryOfAnswers.size()+1];
+ ExcelCell[] summaryTable = new ExcelCell[summaryOfAnswers.size() + 1];
int total = summaryNACount;
- for ( int value : summaryOfAnswers.values() ) {
- total += value;
+ for (int value : summaryOfAnswers.values()) {
+ total += value;
}
int i = 0;
if (question.getType() == AssessmentConstants.QUESTION_TYPE_MULTIPLE_CHOICE
|| question.getType() == AssessmentConstants.QUESTION_TYPE_SHORT_ANSWER
- || question.getType() == AssessmentConstants.QUESTION_TYPE_NUMERICAL ) {
- for (AssessmentQuestionOption option : question.getOptions()) {
- summaryTable[i] = new ExcelCell(valueAsPercentage(summaryOfAnswers.get(option.getUid()), total), false);
- if ( option.getGrade() > 0 ) {
- summaryTable[i].setColor(IndexedColors.GREEN);
+ || question.getType() == AssessmentConstants.QUESTION_TYPE_NUMERICAL) {
+ for (AssessmentQuestionOption option : question.getOptions()) {
+ summaryTable[i] = new ExcelCell(valueAsPercentage(summaryOfAnswers.get(option.getUid()), total), false);
+ if (option.getGrade() > 0) {
+ summaryTable[i].setColor(IndexedColors.GREEN);
+ }
+ i++;
}
- i++;
- }
- summaryTable[i++] = new ExcelCell(valueAsPercentage(summaryNACount, total), false);
+ summaryTable[i++] = new ExcelCell(valueAsPercentage(summaryNACount, total), false);
} else {
- summaryTable = new ExcelCell[3];
- summaryTable[0] = new ExcelCell(valueAsPercentage(summaryOfAnswers.get(trueKey), total), false);
- summaryTable[1] = new ExcelCell(valueAsPercentage(summaryOfAnswers.get(falseKey), total), false);
- summaryTable[2] = new ExcelCell(valueAsPercentage(summaryNACount,total), false);
- summaryTable[question.getCorrectAnswer() ? 0 : 1].setColor(IndexedColors.GREEN);
+ summaryTable = new ExcelCell[3];
+ summaryTable[0] = new ExcelCell(valueAsPercentage(summaryOfAnswers.get(trueKey), total), false);
+ summaryTable[1] = new ExcelCell(valueAsPercentage(summaryOfAnswers.get(falseKey), total), false);
+ summaryTable[2] = new ExcelCell(valueAsPercentage(summaryNACount, total), false);
+ summaryTable[question.getCorrectAnswer() ? 0 : 1].setColor(IndexedColors.GREEN);
}
return summaryTable;
}
-
/**
* Used only for excell export (for getUserSummaryData() method).
*/
@@ -1912,11 +1941,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);
}
@@ -1960,7 +1989,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())) {
@@ -2006,7 +2035,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())
@@ -2017,7 +2046,7 @@
}
// create list of added references
- List addedReferences = new ArrayList();
+ List addedReferences = new ArrayList<>();
for (QuestionReference newReference : newReferences) {
boolean isNewReferenceMetInOldReferences = false;
@@ -2045,7 +2074,7 @@
user.getUserId());
AssessmentResult lastFinishedAssessmentResult = (assessmentResults.isEmpty()) ? null
: assessmentResults.get(assessmentResults.size() - 1);
-
+
//add autosave assessmentResult as well
AssessmentResult lastAssessmentResult = getLastAssessmentResult(assessment.getUid(), user.getUserId());
if (lastAssessmentResult != null && lastAssessmentResult.getFinishDate() == null) {
@@ -2126,7 +2155,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()
@@ -2234,7 +2263,7 @@
public boolean isGroupedActivity(long toolContentID) {
return toolService.isGroupedActivity(toolContentID);
}
-
+
@Override
public void auditLogStartEditingActivityInMonitor(long toolContentID) {
toolService.auditLogStartEditingActivityInMonitor(toolContentID);
@@ -2261,7 +2290,6 @@
eventNotificationService.notifyLessonMonitors(sessionId, message, false);
}
-
@Override
public List getMarksArray(Long sessionId) {
return assessmentUserDao.getRawUserMarksBySession(sessionId);
@@ -2272,66 +2300,70 @@
return assessmentUserDao.getRawLeaderMarksByToolContentId(toolContentId);
}
- private LinkedHashMap getMarksSummaryForSession(List userDtos, float minGrade, float maxGrade, Integer numBuckets) {
+ private LinkedHashMap getMarksSummaryForSession(List userDtos, float minGrade,
+ float maxGrade, Integer numBuckets) {
- LinkedHashMap summary = new LinkedHashMap();
- TreeMap inProgress = new TreeMap();
-
- if ( numBuckets == null )
+ LinkedHashMap summary = new LinkedHashMap<>();
+ TreeMap inProgress = new TreeMap<>();
+
+ if (numBuckets == null) {
numBuckets = 10;
-
+ }
+
int bucketSize = 1;
- int intMinGrade = (int)Math.floor(minGrade);
+ int intMinGrade = (int) Math.floor(minGrade);
float gradeDifference = maxGrade - minGrade;
- if ( gradeDifference <= 10 ) {
- for ( int i= intMinGrade; i <= (int)Math.ceil(maxGrade); i++ ) {
+ if (gradeDifference <= 10) {
+ for (int i = intMinGrade; i <= (int) Math.ceil(maxGrade); i++) {
inProgress.put(i, 0);
}
} else {
int intGradeDifference = (int) Math.ceil(gradeDifference);
- bucketSize = (int) Math.ceil(intGradeDifference / numBuckets);
- for ( int i=intMinGrade; i <= maxGrade; i = i+bucketSize ) {
+ bucketSize = (int) Math.ceil(intGradeDifference / numBuckets);
+ for (int i = intMinGrade; i <= maxGrade; i = i + bucketSize) {
inProgress.put(i, 0);
}
}
-
+
for (AssessmentUserDTO userDto : userDtos) {
float grade = userDto.getGrade();
int bucketStart = intMinGrade;
- int bucketStop = bucketStart+bucketSize;
+ int bucketStop = bucketStart + bucketSize;
boolean looking = true;
- while ( bucketStart <= maxGrade && looking ) {
- if ( grade >= bucketStart && grade < bucketStop ) {
+ while (bucketStart <= maxGrade && looking) {
+ if (grade >= bucketStart && grade < bucketStop) {
inProgress.put(bucketStart, inProgress.get(bucketStart) + 1);
looking = false;
} else {
bucketStart = bucketStop;
- bucketStop = bucketStart+bucketSize;
+ bucketStop = bucketStart + bucketSize;
}
}
}
-
- for ( Map.Entry entry : inProgress.entrySet() ) {
+
+ for (Map.Entry entry : inProgress.entrySet()) {
String key;
- if ( bucketSize == 1 )
+ if (bucketSize == 1) {
key = entry.getKey().toString();
- else {
- if ( maxGrade >= entry.getKey() && maxGrade <= entry.getKey()+bucketSize-1) {
- if ( (int)maxGrade == entry.getKey() )
- key = NumberUtil.formatLocalisedNumber(maxGrade, (Locale)null, 2);
- else
+ } else {
+ if (maxGrade >= entry.getKey() && maxGrade <= entry.getKey() + bucketSize - 1) {
+ if ((int) maxGrade == entry.getKey()) {
+ key = NumberUtil.formatLocalisedNumber(maxGrade, (Locale) null, 2);
+ } else {
key = new StringBuilder().append(entry.getKey()).append(" - ")
- .append(NumberUtil.formatLocalisedNumber(maxGrade, (Locale)null, 2)).toString();
+ .append(NumberUtil.formatLocalisedNumber(maxGrade, (Locale) null, 2)).toString();
+ }
} else {
- key = new StringBuilder().append(entry.getKey()).append(" - ").append(entry.getKey()+bucketSize-.01).toString();
+ key = new StringBuilder().append(entry.getKey()).append(" - ")
+ .append(entry.getKey() + bucketSize - .01).toString();
}
}
summary.put(key, entry.getValue());
}
-
+
return summary;
}
-
+
// *****************************************************************************
// private methods
// *****************************************************************************
@@ -2768,116 +2800,126 @@
Date startDate = null;
Date finishDate = null;
for (AssessmentResult result : results) {
- if (startDate == null || (result.getStartDate() != null && result.getStartDate().before(startDate)))
+ if (startDate == null || (result.getStartDate() != null && result.getStartDate().before(startDate))) {
startDate = result.getStartDate();
- if (finishDate == null || (result.getFinishDate() != null && result.getFinishDate().after(finishDate)))
+ }
+ if (finishDate == null || (result.getFinishDate() != null && result.getFinishDate().after(finishDate))) {
finishDate = result.getFinishDate();
+ }
}
- if (learner.isSessionFinished())
+ if (learner.isSessionFinished()) {
return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_COMPLETED, startDate, finishDate);
- else
+ } else {
return new ToolCompletionStatus(ToolCompletionStatus.ACTIVITY_ATTEMPTED, startDate, null);
+ }
}
// ****************** REST methods *************************
/**
* Rest call to create a new Assessment content. Required fields in toolContentJSON: "title", "instructions",
* "questions", "firstName", "lastName", "lastName", "questions" and "references".
*
- * The questions entry should be a JSONArray containing JSON objects, which in turn must contain "questionTitle",
+ * The questions entry should be a ArrayNode containing JSON objects, which in turn must contain "questionTitle",
* "questionText", "displayOrder" (Integer), "type" (Integer). If the type is Multiple Choice, Numerical or Matching
- * Pairs then a JSONArray "answers" is required.
+ * Pairs then a ArrayNode "answers" is required.
*
- * The answers entry should be JSONArray containing JSON objects, which in turn must contain "answerText" or
+ * The answers entry should be ArrayNode containing JSON objects, which in turn must contain "answerText" or
* "answerFloat", "displayOrder" (Integer), "grade" (Integer).
*
- * The references entry should be a JSONArray containing JSON objects, which in turn must contain "displayOrder"
+ * The references entry should be a ArrayNode containing JSON objects, which in turn must contain "displayOrder"
* (Integer), "questionDisplayOrder" (Integer - to match to the question). It may also have "defaultGrade" (Integer)
* and "randomQuestion" (Boolean)
+ *
+ * @throws IOException
*/
@SuppressWarnings("unchecked")
@Override
- public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON)
- throws JSONException {
+ public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON)
+ throws IOException {
Assessment assessment = new Assessment();
assessment.setContentId(toolContentID);
- assessment.setTitle(toolContentJSON.getString(RestTags.TITLE));
- assessment.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS));
+ assessment.setTitle(toolContentJSON.get(RestTags.TITLE).asText());
+ assessment.setInstructions(toolContentJSON.get(RestTags.INSTRUCTIONS).asText());
assessment.setCreated(new Date());
- assessment.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE));
- assessment.setReflectInstructions(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, (String) null));
- assessment.setAllowGradesAfterAttempt(JsonUtil.opt(toolContentJSON, "allowGradesAfterAttempt", Boolean.FALSE));
- assessment.setAllowHistoryResponses(JsonUtil.opt(toolContentJSON, "allowHistoryResponses", Boolean.FALSE));
+ assessment.setReflectOnActivity(
+ JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE));
+ assessment.setReflectInstructions(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS));
+ assessment.setAllowGradesAfterAttempt(
+ JsonUtil.optBoolean(toolContentJSON, "allowGradesAfterAttempt", Boolean.FALSE));
+ assessment
+ .setAllowHistoryResponses(JsonUtil.optBoolean(toolContentJSON, "allowHistoryResponses", Boolean.FALSE));
assessment.setAllowOverallFeedbackAfterQuestion(
- JsonUtil.opt(toolContentJSON, "allowOverallFeedbackAfterQuestion", Boolean.FALSE));
- assessment.setAllowQuestionFeedback(JsonUtil.opt(toolContentJSON, "allowQuestionFeedback", Boolean.FALSE));
+ JsonUtil.optBoolean(toolContentJSON, "allowOverallFeedbackAfterQuestion", Boolean.FALSE));
+ assessment
+ .setAllowQuestionFeedback(JsonUtil.optBoolean(toolContentJSON, "allowQuestionFeedback", Boolean.FALSE));
assessment.setAllowRightAnswersAfterQuestion(
- JsonUtil.opt(toolContentJSON, "allowRightAnswersAfterQuestion", Boolean.FALSE));
+ JsonUtil.optBoolean(toolContentJSON, "allowRightAnswersAfterQuestion", Boolean.FALSE));
assessment.setAllowWrongAnswersAfterQuestion(
- JsonUtil.opt(toolContentJSON, "allowWrongAnswersAfterQuestion", Boolean.FALSE));
- assessment.setAttemptsAllowed(JsonUtil.opt(toolContentJSON, "attemptsAllows", 1));
+ JsonUtil.optBoolean(toolContentJSON, "allowWrongAnswersAfterQuestion", Boolean.FALSE));
+ assessment.setAttemptsAllowed(JsonUtil.optInt(toolContentJSON, "attemptsAllows", 1));
assessment.setDefineLater(false);
- assessment.setDisplaySummary(JsonUtil.opt(toolContentJSON, "displaySummary", Boolean.FALSE));
+ assessment.setDisplaySummary(JsonUtil.optBoolean(toolContentJSON, "displaySummary", Boolean.FALSE));
assessment.setNotifyTeachersOnAttemptCompletion(
- JsonUtil.opt(toolContentJSON, "notifyTeachersOnAttemptCompletion", Boolean.FALSE));
- assessment.setNumbered(JsonUtil.opt(toolContentJSON, "numbered", Boolean.TRUE));
- assessment.setPassingMark(JsonUtil.opt(toolContentJSON, "passingMark", 0));
- assessment.setQuestionsPerPage(JsonUtil.opt(toolContentJSON, "questionsPerPage", 0));
- assessment.setReflectInstructions(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, ""));
- assessment.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE));
- assessment.setShuffled(JsonUtil.opt(toolContentJSON, "shuffled", Boolean.FALSE));
- assessment.setTimeLimit(JsonUtil.opt(toolContentJSON, "timeLimit", 0));
+ JsonUtil.optBoolean(toolContentJSON, "notifyTeachersOnAttemptCompletion", Boolean.FALSE));
+ assessment.setNumbered(JsonUtil.optBoolean(toolContentJSON, "numbered", Boolean.TRUE));
+ assessment.setPassingMark(JsonUtil.optInt(toolContentJSON, "passingMark", 0));
+ assessment.setQuestionsPerPage(JsonUtil.optInt(toolContentJSON, "questionsPerPage", 0));
+ assessment.setReflectInstructions(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, ""));
+ assessment.setReflectOnActivity(
+ JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE));
+ assessment.setShuffled(JsonUtil.optBoolean(toolContentJSON, "shuffled", Boolean.FALSE));
+ assessment.setTimeLimit(JsonUtil.optInt(toolContentJSON, "timeLimit", 0));
assessment.setUseSelectLeaderToolOuput(
- JsonUtil.opt(toolContentJSON, RestTags.USE_SELECT_LEADER_TOOL_OUTPUT, Boolean.FALSE));
+ JsonUtil.optBoolean(toolContentJSON, RestTags.USE_SELECT_LEADER_TOOL_OUTPUT, Boolean.FALSE));
// submission deadline set in monitoring
if (toolContentJSON.has("overallFeedback")) {
- throw new JSONException(
+ throw new IOException(
"Assessment Tool does not support Overall Feedback for REST Authoring. " + toolContentJSON);
}
AssessmentUser assessmentUser = getUserByIDAndContent(userID.longValue(), toolContentID);
if (assessmentUser == null) {
assessmentUser = new AssessmentUser();
- assessmentUser.setFirstName(toolContentJSON.getString("firstName"));
- assessmentUser.setLastName(toolContentJSON.getString("lastName"));
- assessmentUser.setLoginName(toolContentJSON.getString("loginName"));
+ assessmentUser.setFirstName(toolContentJSON.get("firstName").asText());
+ assessmentUser.setLastName(toolContentJSON.get("lastName").asText());
+ assessmentUser.setLoginName(toolContentJSON.get("loginName").asText());
assessmentUser.setAssessment(assessment);
}
assessment.setCreatedBy(assessmentUser);
// **************************** Set the question bank *********************
- JSONArray questions = toolContentJSON.getJSONArray("questions");
+ ArrayNode questions = JsonUtil.optArray(toolContentJSON, "questions");
Set newQuestionSet = assessment.getQuestions(); // the Assessment constructor will set up the collection
- for (int i = 0; i < questions.length(); i++) {
- JSONObject questionJSONData = (JSONObject) questions.get(i);
+ for (JsonNode questionJSONData : questions) {
AssessmentQuestion question = new AssessmentQuestion();
- short type = (short) questionJSONData.getInt("type");
+ short type = JsonUtil.optInt(questionJSONData, "type").shortValue();
question.setType(type);
- question.setTitle(questionJSONData.getString(RestTags.QUESTION_TITLE));
- question.setQuestion(questionJSONData.getString(RestTags.QUESTION_TEXT));
- question.setSequenceId(questionJSONData.getInt(RestTags.DISPLAY_ORDER));
+ question.setTitle(questionJSONData.get(RestTags.QUESTION_TITLE).asText());
+ question.setQuestion(questionJSONData.get(RestTags.QUESTION_TEXT).asText());
+ question.setSequenceId(JsonUtil.optInt(questionJSONData, RestTags.DISPLAY_ORDER));
- question.setAllowRichEditor(JsonUtil.opt(questionJSONData, RestTags.ALLOW_RICH_TEXT_EDITOR, Boolean.FALSE));
- question.setAnswerRequired(JsonUtil.opt(questionJSONData, "answerRequired", Boolean.FALSE));
- question.setCaseSensitive(JsonUtil.opt(questionJSONData, "caseSensitive", Boolean.FALSE));
- question.setCorrectAnswer(JsonUtil.opt(questionJSONData, "correctAnswer", Boolean.FALSE));
- question.setDefaultGrade(JsonUtil.opt(questionJSONData, "defaultGrade", 1));
- question.setFeedback(JsonUtil.opt(questionJSONData, "feedback", (String) null));
- question.setFeedbackOnCorrect(JsonUtil.opt(questionJSONData, "feedbackOnCorrect", (String) null));
- question.setFeedbackOnIncorrect(JsonUtil.opt(questionJSONData, "feedbackOnIncorrect", (String) null));
- question.setFeedbackOnPartiallyCorrect(
- JsonUtil.opt(questionJSONData, "feedbackOnPartiallyCorrect", (String) null));
- question.setGeneralFeedback(JsonUtil.opt(questionJSONData, "generalFeedback", ""));
- question.setMaxWordsLimit(JsonUtil.opt(questionJSONData, "maxWordsLimit", 0));
- question.setMinWordsLimit(JsonUtil.opt(questionJSONData, "minWordsLimit", 0));
- question.setMultipleAnswersAllowed(JsonUtil.opt(questionJSONData, "multipleAnswersAllowed", Boolean.FALSE));
+ question.setAllowRichEditor(
+ JsonUtil.optBoolean(questionJSONData, RestTags.ALLOW_RICH_TEXT_EDITOR, Boolean.FALSE));
+ question.setAnswerRequired(JsonUtil.optBoolean(questionJSONData, "answerRequired", Boolean.FALSE));
+ question.setCaseSensitive(JsonUtil.optBoolean(questionJSONData, "caseSensitive", Boolean.FALSE));
+ question.setCorrectAnswer(JsonUtil.optBoolean(questionJSONData, "correctAnswer", Boolean.FALSE));
+ question.setDefaultGrade(JsonUtil.optInt(questionJSONData, "defaultGrade", 1));
+ question.setFeedback(JsonUtil.optString(questionJSONData, "feedback"));
+ question.setFeedbackOnCorrect(JsonUtil.optString(questionJSONData, "feedbackOnCorrect"));
+ question.setFeedbackOnIncorrect(JsonUtil.optString(questionJSONData, "feedbackOnIncorrect"));
+ question.setFeedbackOnPartiallyCorrect(JsonUtil.optString(questionJSONData, "feedbackOnPartiallyCorrect"));
+ question.setGeneralFeedback(JsonUtil.optString(questionJSONData, "generalFeedback", ""));
+ question.setMaxWordsLimit(JsonUtil.optInt(questionJSONData, "maxWordsLimit", 0));
+ question.setMinWordsLimit(JsonUtil.optInt(questionJSONData, "minWordsLimit", 0));
+ question.setMultipleAnswersAllowed(
+ JsonUtil.optBoolean(questionJSONData, "multipleAnswersAllowed", Boolean.FALSE));
question.setIncorrectAnswerNullifiesMark(
- JsonUtil.opt(questionJSONData, "incorrectAnswerNullifiesMark", Boolean.FALSE));
- question.setPenaltyFactor(Float.parseFloat(JsonUtil.opt(questionJSONData, "penaltyFactor", "0.0")));
+ JsonUtil.optBoolean(questionJSONData, "incorrectAnswerNullifiesMark", Boolean.FALSE));
+ question.setPenaltyFactor(JsonUtil.optDouble(questionJSONData, "penaltyFactor", 0.0).floatValue());
// question.setUnits(units); Needed for numerical type question
if ((type == AssessmentConstants.QUESTION_TYPE_MATCHING_PAIRS)
@@ -2886,22 +2928,21 @@
|| (type == AssessmentConstants.QUESTION_TYPE_MARK_HEDGING)) {
if (!questionJSONData.has(RestTags.ANSWERS)) {
- throw new JSONException("REST Authoring is missing answers for a question of type " + type
- + ". Data:" + toolContentJSON);
+ throw new IOException("REST Authoring is missing answers for a question of type " + type + ". Data:"
+ + toolContentJSON);
}
- Set optionList = new LinkedHashSet();
- JSONArray optionsData = questionJSONData.getJSONArray(RestTags.ANSWERS);
- for (int j = 0; j < optionsData.length(); j++) {
- JSONObject answerData = (JSONObject) optionsData.get(j);
+ Set optionList = new LinkedHashSet<>();
+ ArrayNode optionsData = JsonUtil.optArray(questionJSONData, RestTags.ANSWERS);
+ for (JsonNode answerData : optionsData) {
AssessmentQuestionOption option = new AssessmentQuestionOption();
- option.setSequenceId(answerData.getInt(RestTags.DISPLAY_ORDER));
- option.setGrade(Float.parseFloat(answerData.getString("grade")));
- option.setCorrect(Boolean.parseBoolean(JsonUtil.opt(answerData, "correct", "false")));
- option.setAcceptedError(Float.parseFloat(JsonUtil.opt(answerData, "acceptedError", "0.0")));
- option.setFeedback(JsonUtil.opt(answerData, "feedback", (String) null));
- option.setOptionString(JsonUtil.opt(answerData, RestTags.ANSWER_TEXT, (String) null));
- option.setOptionFloat(Float.parseFloat(JsonUtil.opt(answerData, "answerFloat", "0.0")));
+ option.setSequenceId(JsonUtil.optInt(answerData, RestTags.DISPLAY_ORDER));
+ option.setGrade(answerData.get("grade").floatValue());
+ option.setCorrect(JsonUtil.optBoolean(answerData, "correct", false));
+ option.setAcceptedError(JsonUtil.optDouble(answerData, "acceptedError", 0.0).floatValue());
+ option.setFeedback(JsonUtil.optString(answerData, "feedback"));
+ option.setOptionString(JsonUtil.optString(answerData, RestTags.ANSWER_TEXT));
+ option.setOptionFloat(JsonUtil.optDouble(answerData, "answerFloat", 0.0).floatValue());
// option.setQuestion(question); can't find the use for this field yet!
optionList.add(option);
}
@@ -2913,23 +2954,23 @@
}
// **************************** Now set up the references to the questions in the bank *********************
- JSONArray references = toolContentJSON.getJSONArray("references");
+ ArrayNode references = JsonUtil.optArray(toolContentJSON, "references");
Set newReferenceSet = assessment.getQuestionReferences(); // the Assessment constructor will set up the
- // collection
- for (int i = 0; i < references.length(); i++) {
- JSONObject referenceJSONData = (JSONObject) references.get(i);
+
+ ;// collection
+ for (JsonNode referenceJSONData : references) {
QuestionReference reference = new QuestionReference();
reference.setType((short) 0);
- reference.setDefaultGrade(JsonUtil.opt(referenceJSONData, "defaultGrade", 1));
- reference.setSequenceId(referenceJSONData.getInt(RestTags.DISPLAY_ORDER));
+ reference.setDefaultGrade(JsonUtil.optInt(referenceJSONData, "defaultGrade", 1));
+ reference.setSequenceId(JsonUtil.optInt(referenceJSONData, RestTags.DISPLAY_ORDER));
AssessmentQuestion matchingQuestion = matchQuestion(newQuestionSet,
- referenceJSONData.getInt("questionDisplayOrder"));
+ JsonUtil.optInt(referenceJSONData, "questionDisplayOrder"));
if (matchingQuestion == null) {
- throw new JSONException("Unable to find matching question for displayOrder "
+ throw new IOException("Unable to find matching question for displayOrder "
+ referenceJSONData.get("questionDisplayOrder") + ". Data:" + toolContentJSON);
}
reference.setQuestion(matchingQuestion);
- reference.setRandomQuestion(JsonUtil.opt(referenceJSONData, "randomQuestion", Boolean.FALSE));
+ reference.setRandomQuestion(JsonUtil.optBoolean(referenceJSONData, "randomQuestion", Boolean.FALSE));
reference.setTitle(null);
newReferenceSet.add(reference);
}
@@ -2951,10 +2992,10 @@
}
// TODO Implement REST support for all types and then remove checkType method
- void checkType(short type) throws JSONException {
+ void checkType(short type) throws IOException {
if ((type != AssessmentConstants.QUESTION_TYPE_ESSAY)
&& (type != AssessmentConstants.QUESTION_TYPE_MULTIPLE_CHOICE)) {
- throw new JSONException(
+ throw new IOException(
"Assessment Tool does not support REST Authoring for anything but Essay Type and Multiple Choice. Found type "
+ type);
}
Index: lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/service/ForumService.java
===================================================================
diff -u -rb67c428939ed96f08f56192d54b8ee55d8ab89d2 -r2c03060b238558d183472f0066ba003c76d00fd0
--- lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/service/ForumService.java (.../ForumService.java) (revision b67c428939ed96f08f56192d54b8ee55d8ab89d2)
+++ lams_tool_forum/src/java/org/lamsfoundation/lams/tool/forum/service/ForumService.java (.../ForumService.java) (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -42,9 +42,6 @@
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.upload.FormFile;
-import org.apache.tomcat.util.json.JSONArray;
-import org.apache.tomcat.util.json.JSONException;
-import org.apache.tomcat.util.json.JSONObject;
import org.lamsfoundation.lams.contentrepository.ICredentials;
import org.lamsfoundation.lams.contentrepository.ITicket;
import org.lamsfoundation.lams.contentrepository.NodeKey;
@@ -114,6 +111,9 @@
import org.lamsfoundation.lams.util.MessageService;
import org.lamsfoundation.lams.util.audit.IAuditService;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
/**
*
* @author Steve.Ni
@@ -1514,50 +1514,49 @@
/**
* Used by the Rest calls to create content. Mandatory fields in toolContentJSON: title, instructions, topics.
- * Topics must contain a JSONArray of JSONObject objects, which have the following mandatory fields: subject, body
+ * Topics must contain a ArrayNode of ObjectNode objects, which have the following mandatory fields: subject, body
* There will usually be at least one topic object in the Topics array but the array may be of zero length.
*/
@Override
- public void createRestToolContent(Integer userID, Long toolContentID, JSONObject toolContentJSON)
- throws JSONException {
+ public void createRestToolContent(Integer userID, Long toolContentID, ObjectNode toolContentJSON) {
Forum forum = new Forum();
Date updateDate = new Date();
forum.setCreated(updateDate);
forum.setUpdated(updateDate);
forum.setContentId(toolContentID);
- forum.setTitle(toolContentJSON.getString(RestTags.TITLE));
- forum.setInstructions(toolContentJSON.getString(RestTags.INSTRUCTIONS));
+ forum.setTitle(JsonUtil.optString(toolContentJSON, RestTags.TITLE));
+ forum.setInstructions(JsonUtil.optString(toolContentJSON, RestTags.INSTRUCTIONS));
- forum.setAllowAnonym(JsonUtil.opt(toolContentJSON, "allowAnonym", Boolean.FALSE));
- forum.setAllowEdit(JsonUtil.opt(toolContentJSON, "allowEdit", Boolean.TRUE)); // defaults to true in the default
- // entry in the db
- forum.setAllowNewTopic(JsonUtil.opt(toolContentJSON, "allowNewTopic", Boolean.TRUE)); // defaults to true in the
- // default entry in the db
- forum.setAllowRateMessages(JsonUtil.opt(toolContentJSON, "allowRateMessages", Boolean.FALSE));
- forum.setAllowRichEditor(JsonUtil.opt(toolContentJSON, RestTags.ALLOW_RICH_TEXT_EDITOR, Boolean.FALSE));
- forum.setAllowUpload(JsonUtil.opt(toolContentJSON, "allowUpload", Boolean.FALSE));
+ forum.setAllowAnonym(JsonUtil.optBoolean(toolContentJSON, "allowAnonym", Boolean.FALSE));
+ forum.setAllowEdit(JsonUtil.optBoolean(toolContentJSON, "allowEdit", Boolean.TRUE)); // defaults to true in the default
+ // entry in the db
+ forum.setAllowNewTopic(JsonUtil.optBoolean(toolContentJSON, "allowNewTopic", Boolean.TRUE)); // defaults to true in the
+ // default entry in the db
+ forum.setAllowRateMessages(JsonUtil.optBoolean(toolContentJSON, "allowRateMessages", Boolean.FALSE));
+ forum.setAllowRichEditor(JsonUtil.optBoolean(toolContentJSON, RestTags.ALLOW_RICH_TEXT_EDITOR, Boolean.FALSE));
+ forum.setAllowUpload(JsonUtil.optBoolean(toolContentJSON, "allowUpload", Boolean.FALSE));
forum.setContentInUse(false);
forum.setDefineLater(false);
- forum.setLimitedMaxCharacters(JsonUtil.opt(toolContentJSON, "limitedMaxCharacters", Boolean.TRUE));
- forum.setLimitedMinCharacters(JsonUtil.opt(toolContentJSON, "limitedMinCharacters", Boolean.FALSE));
- forum.setLockWhenFinished(JsonUtil.opt(toolContentJSON, "lockWhenFinished", Boolean.FALSE));
- forum.setMaxCharacters(JsonUtil.opt(toolContentJSON, "maxCharacters", 5000)); // defaults to 5000 chars in the
- // default entry in the db.
- forum.setMaximumRate(JsonUtil.opt(toolContentJSON, "maximumRate", 0));
- forum.setMaximumReply(JsonUtil.opt(toolContentJSON, "maximumReply", 0));
- forum.setMinCharacters(JsonUtil.opt(toolContentJSON, "minCharacters", 0));
- forum.setMinimumRate(JsonUtil.opt(toolContentJSON, "minimumRate", 0));
- forum.setMinimumReply(JsonUtil.opt(toolContentJSON, "minimumReply", 0));
+ forum.setLimitedMaxCharacters(JsonUtil.optBoolean(toolContentJSON, "limitedMaxCharacters", Boolean.TRUE));
+ forum.setLimitedMinCharacters(JsonUtil.optBoolean(toolContentJSON, "limitedMinCharacters", Boolean.FALSE));
+ forum.setLockWhenFinished(JsonUtil.optBoolean(toolContentJSON, "lockWhenFinished", Boolean.FALSE));
+ forum.setMaxCharacters(JsonUtil.optInt(toolContentJSON, "maxCharacters", 5000)); // defaults to 5000 chars in the
+ // default entry in the db.
+ forum.setMaximumRate(JsonUtil.optInt(toolContentJSON, "maximumRate", 0));
+ forum.setMaximumReply(JsonUtil.optInt(toolContentJSON, "maximumReply", 0));
+ forum.setMinCharacters(JsonUtil.optInt(toolContentJSON, "minCharacters", 0));
+ forum.setMinimumRate(JsonUtil.optInt(toolContentJSON, "minimumRate", 0));
+ forum.setMinimumReply(JsonUtil.optInt(toolContentJSON, "minimumReply", 0));
forum.setNotifyLearnersOnForumPosting(
- JsonUtil.opt(toolContentJSON, "notifyLearnersOnForumPosting", Boolean.FALSE));
+ JsonUtil.optBoolean(toolContentJSON, "notifyLearnersOnForumPosting", Boolean.FALSE));
forum.setNotifyLearnersOnMarkRelease(
- JsonUtil.opt(toolContentJSON, "notifyLearnersOnMarkRelease", Boolean.FALSE));
+ JsonUtil.optBoolean(toolContentJSON, "notifyLearnersOnMarkRelease", Boolean.FALSE));
forum.setNotifyTeachersOnForumPosting(
- JsonUtil.opt(toolContentJSON, "notifyTeachersOnForumPosting", Boolean.FALSE));
- forum.setReflectInstructions((String) JsonUtil.opt(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS, null));
- forum.setReflectOnActivity(JsonUtil.opt(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE));
+ JsonUtil.optBoolean(toolContentJSON, "notifyTeachersOnForumPosting", Boolean.FALSE));
+ forum.setReflectInstructions(JsonUtil.optString(toolContentJSON, RestTags.REFLECT_INSTRUCTIONS));
+ forum.setReflectOnActivity(JsonUtil.optBoolean(toolContentJSON, RestTags.REFLECT_ON_ACTIVITY, Boolean.FALSE));
// submissionDeadline is set in monitoring
// *******************************Handle user*******************
@@ -1571,27 +1570,27 @@
// UserDTO user = (UserDTO) ss.getAttribute(AttributeNames.USER);
ForumUser forumUser = getUserByID(userID.longValue());
if (forumUser == null) {
- forumUser = new ForumUser(userID.longValue(), toolContentJSON.getString("firstName"),
- toolContentJSON.getString("lastName"), toolContentJSON.getString("loginName"));
+ forumUser = new ForumUser(userID.longValue(), JsonUtil.optString(toolContentJSON, "firstName"),
+ JsonUtil.optString(toolContentJSON, "lastName"), JsonUtil.optString(toolContentJSON, "loginName"));
getForumUserDao().save(forumUser);
}
forum.setCreatedBy(forumUser);
updateForum(forum);
// **************************** Handle topic *********************
- JSONArray topics = toolContentJSON.getJSONArray("topics");
- for (int i = 0; i < topics.length(); i++) {
- JSONObject msgData = (JSONObject) topics.get(i);
+ ArrayNode topics = JsonUtil.optArray(toolContentJSON, "topics");
+ for (int i = 0; i < topics.size(); i++) {
+ ObjectNode msgData = (ObjectNode) topics.get(i);
Message newMsg = new Message();
// newMsg.setAttachments(attachments); TODO
newMsg.setCreatedBy(forumUser);
newMsg.setCreated(updateDate);
newMsg.setModifiedBy(null);
newMsg.setUpdated(updateDate);
- newMsg.setSubject(msgData.getString("subject"));
- newMsg.setBody(msgData.getString("body"));
+ newMsg.setSubject(JsonUtil.optString(msgData, "subject"));
+ newMsg.setBody(JsonUtil.optString(msgData, "body"));
newMsg.setForum(forum);
newMsg.setHideFlag(false);
// newMsg.setIsAnonymous(false); Does not appear on authoring interface
Index: lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/service/McService.java
===================================================================
diff -u
--- lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/service/McService.java (revision 0)
+++ lams_tool_lamc/src/java/org/lamsfoundation/lams/tool/mc/service/McService.java (revision 2c03060b238558d183472f0066ba003c76d00fd0)
@@ -0,0 +1,1976 @@
+/***************************************************************************
+ * 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 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.tool.mc.service;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.SortedMap;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+import javax.servlet.http.HttpSession;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.log4j.Logger;
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFCellStyle;
+import org.apache.poi.hssf.usermodel.HSSFRow;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.ss.usermodel.CellStyle;
+import org.apache.poi.ss.usermodel.Font;
+import org.apache.poi.ss.usermodel.IndexedColors;
+import org.lamsfoundation.lams.contentrepository.client.IToolContentHandler;
+import org.lamsfoundation.lams.gradebook.service.IGradebookService;
+import org.lamsfoundation.lams.learning.service.ILearnerService;
+import org.lamsfoundation.lams.learningdesign.service.ExportToolContentException;
+import org.lamsfoundation.lams.learningdesign.service.IExportToolContentService;
+import org.lamsfoundation.lams.learningdesign.service.ImportToolContentException;
+import org.lamsfoundation.lams.notebook.model.NotebookEntry;
+import org.lamsfoundation.lams.notebook.service.CoreNotebookConstants;
+import org.lamsfoundation.lams.notebook.service.ICoreNotebookService;
+import org.lamsfoundation.lams.rest.RestTags;
+import org.lamsfoundation.lams.rest.ToolRestManager;
+import org.lamsfoundation.lams.tool.IToolVO;
+import org.lamsfoundation.lams.tool.ToolCompletionStatus;
+import org.lamsfoundation.lams.tool.ToolContentManager;
+import org.lamsfoundation.lams.tool.ToolOutput;
+import org.lamsfoundation.lams.tool.ToolOutputDefinition;
+import org.lamsfoundation.lams.tool.ToolSessionExportOutputData;
+import org.lamsfoundation.lams.tool.ToolSessionManager;
+import org.lamsfoundation.lams.tool.exception.DataMissingException;
+import org.lamsfoundation.lams.tool.exception.ToolException;
+import org.lamsfoundation.lams.tool.mc.McAppConstants;
+import org.lamsfoundation.lams.tool.mc.dao.IMcContentDAO;
+import org.lamsfoundation.lams.tool.mc.dao.IMcOptionsContentDAO;
+import org.lamsfoundation.lams.tool.mc.dao.IMcQueContentDAO;
+import org.lamsfoundation.lams.tool.mc.dao.IMcSessionDAO;
+import org.lamsfoundation.lams.tool.mc.dao.IMcUserDAO;
+import org.lamsfoundation.lams.tool.mc.dao.IMcUsrAttemptDAO;
+import org.lamsfoundation.lams.tool.mc.dto.AnswerDTO;
+import org.lamsfoundation.lams.tool.mc.dto.LeaderResultsDTO;
+import org.lamsfoundation.lams.tool.mc.dto.McOptionDTO;
+import org.lamsfoundation.lams.tool.mc.dto.McQuestionDTO;
+import org.lamsfoundation.lams.tool.mc.dto.McSessionMarkDTO;
+import org.lamsfoundation.lams.tool.mc.dto.McUserMarkDTO;
+import org.lamsfoundation.lams.tool.mc.dto.ReflectionDTO;
+import org.lamsfoundation.lams.tool.mc.dto.SessionDTO;
+import org.lamsfoundation.lams.tool.mc.dto.ToolOutputDTO;
+import org.lamsfoundation.lams.tool.mc.pojos.McContent;
+import org.lamsfoundation.lams.tool.mc.pojos.McOptsContent;
+import org.lamsfoundation.lams.tool.mc.pojos.McQueContent;
+import org.lamsfoundation.lams.tool.mc.pojos.McQueUsr;
+import org.lamsfoundation.lams.tool.mc.pojos.McSession;
+import org.lamsfoundation.lams.tool.mc.pojos.McUsrAttempt;
+import org.lamsfoundation.lams.tool.mc.util.McSessionComparator;
+import org.lamsfoundation.lams.tool.mc.util.McStringComparator;
+import org.lamsfoundation.lams.tool.service.ILamsToolService;
+import org.lamsfoundation.lams.usermanagement.User;
+import org.lamsfoundation.lams.usermanagement.dto.UserDTO;
+import org.lamsfoundation.lams.usermanagement.service.IUserManagementService;
+import org.lamsfoundation.lams.util.ExcelUtil;
+import org.lamsfoundation.lams.util.JsonUtil;
+import org.lamsfoundation.lams.util.MessageService;
+import org.lamsfoundation.lams.util.NumberUtil;
+import org.lamsfoundation.lams.util.audit.IAuditService;
+import org.lamsfoundation.lams.web.session.SessionManager;
+import org.lamsfoundation.lams.web.util.AttributeNames;
+import org.springframework.dao.DataAccessException;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+/**
+ *
+ * The POJO implementation of Mc service. All business logics of MCQ tool are implemented in this class. It translate
+ * the request from presentation layer and perform appropriate database operation.
+ *
+ * @author Ozgur Demirtas
+ */
+public class McService implements IMcService, ToolContentManager, ToolSessionManager, ToolRestManager, McAppConstants {
+ private static Logger logger = Logger.getLogger(McService.class.getName());
+
+ private IMcContentDAO mcContentDAO;
+ private IMcQueContentDAO mcQueContentDAO;
+ private IMcOptionsContentDAO mcOptionsContentDAO;
+ private IMcSessionDAO mcSessionDAO;
+ private IMcUserDAO mcUserDAO;
+ private IMcUsrAttemptDAO mcUsrAttemptDAO;
+ private MCOutputFactory mcOutputFactory;
+
+ private IAuditService auditService;
+ private IUserManagementService userManagementService;
+ private ILearnerService learnerService;
+ private ILamsToolService toolService;
+ private IToolContentHandler mcToolContentHandler = null;
+ private IExportToolContentService exportContentService;
+ private IGradebookService gradebookService;
+
+ private ICoreNotebookService coreNotebookService;
+
+ private MessageService messageService;
+
+ public McService() {
+ }
+
+ @Override
+ public McQueUsr checkLeaderSelectToolForSessionLeader(McQueUsr user, Long toolSessionId) {
+ if ((user == null) || (toolSessionId == null)) {
+ return null;
+ }
+
+ McSession mcSession = mcSessionDAO.getMcSessionById(toolSessionId);
+ McQueUsr leader = mcSession.getGroupLeader();
+ // check leader select tool for a leader only in case QA tool doesn't know it. As otherwise it will screw
+ // up previous scratches done
+ if (leader == null) {
+
+ Long leaderUserId = toolService.getLeaderUserId(toolSessionId, user.getQueUsrId().intValue());
+ if (leaderUserId != null) {
+
+ leader = getMcUserBySession(leaderUserId, mcSession.getUid());
+
+ // create new user in a DB
+ if (leader == null) {
+ logger.debug("creating new user with userId: " + leaderUserId);
+ User leaderDto = (User) userManagementService.findById(User.class, leaderUserId.intValue());
+ String userName = leaderDto.getLogin();
+ String fullName = leaderDto.getFirstName() + " " + leaderDto.getLastName();
+ leader = new McQueUsr(leaderUserId, userName, fullName, mcSession, new TreeSet());
+ mcUserDAO.saveMcUser(user);
+ }
+
+ // set group leader
+ mcSession.setGroupLeader(leader);
+ mcSessionDAO.updateMcSession(mcSession);
+ }
+ }
+
+ return leader;
+ }
+
+ @Override
+ public void copyAnswersFromLeader(McQueUsr user, McQueUsr leader) {
+
+ if ((user == null) || (leader == null) || user.getUid().equals(leader.getUid())) {
+ return;
+ }
+
+ List leaderAttempts = this.getFinalizedUserAttempts(leader);
+ for (McUsrAttempt leaderAttempt : leaderAttempts) {
+
+ McQueContent question = leaderAttempt.getMcQueContent();
+ McUsrAttempt userAttempt = mcUsrAttemptDAO.getUserAttemptByQuestion(user.getUid(), question.getUid());
+
+ // if response doesn't exist - created mcUsrAttempt in the db
+ if (userAttempt == null) {
+ userAttempt = new McUsrAttempt(leaderAttempt.getAttemptTime(), question, user,
+ leaderAttempt.getMcOptionsContent(), leaderAttempt.getMark(), leaderAttempt.isPassed(),
+ leaderAttempt.isAttemptCorrect());
+ mcUsrAttemptDAO.saveMcUsrAttempt(userAttempt);
+
+ // if it's been changed by the leader
+ } else if (leaderAttempt.getAttemptTime().compareTo(userAttempt.getAttemptTime()) != 0) {
+ userAttempt.setMcOptionsContent(leaderAttempt.getMcOptionsContent());
+ userAttempt.setAttemptTime(leaderAttempt.getAttemptTime());
+ this.updateMcUsrAttempt(userAttempt);
+ }
+
+ user.setNumberOfAttempts(leader.getNumberOfAttempts());
+ user.setLastAttemptTotalMark(leader.getLastAttemptTotalMark());
+ this.updateMcQueUsr(user);
+ }
+ }
+
+ @Override
+ public void createMc(McContent mcContent) throws McApplicationException {
+ try {
+ mcContentDAO.saveMcContent(mcContent);
+ } catch (DataAccessException e) {
+ throw new McApplicationException("Exception occured when lams is creating mc content: " + e.getMessage(),
+ e);
+ }
+ }
+
+ @Override
+ public McContent getMcContent(Long toolContentId) throws McApplicationException {
+ try {
+ return mcContentDAO.findMcContentById(toolContentId);
+ } catch (DataAccessException e) {
+ throw new McApplicationException("Exception occured when lams is loading mc content: " + e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public void setDefineLater(String strToolContentID, boolean value) {
+
+ McContent mcContent = getMcContent(new Long(strToolContentID));
+ if (mcContent != null) {
+ mcContent.setDefineLater(value);
+ updateMc(mcContent);
+ }
+ }
+
+ @Override
+ public void updateQuestion(McQueContent mcQueContent) throws McApplicationException {
+ try {
+ mcQueContentDAO.updateMcQueContent(mcQueContent);
+ } catch (DataAccessException e) {
+ throw new McApplicationException(
+ "Exception occured when lams is updating mc que content: " + e.getMessage(), e);
+ }
+
+ }
+
+ @Override
+ public McQueContent getQuestionByDisplayOrder(final Long displayOrder, final Long mcContentUid)
+ throws McApplicationException {
+ try {
+ return mcQueContentDAO.getQuestionContentByDisplayOrder(displayOrder, mcContentUid);
+ } catch (DataAccessException e) {
+ throw new McApplicationException(
+ "Exception occured when lams is getting mc que content by display order: " + e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public List getAllQuestionsSorted(final long mcContentId) throws McApplicationException {
+ try {
+ return mcQueContentDAO.getAllQuestionEntriesSorted(mcContentId);
+ } catch (DataAccessException e) {
+ throw new McApplicationException(
+ "Exception occured when lams is getting all question entries: " + e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public void saveOrUpdateMcQueContent(McQueContent mcQueContent) throws McApplicationException {
+ try {
+ mcQueContentDAO.saveOrUpdateMcQueContent(mcQueContent);
+ } catch (DataAccessException e) {
+ throw new McApplicationException(
+ "Exception occured when lams is updating mc que content: " + e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public McContent createQuestions(List questionDTOs, McContent content) {
+
+ int displayOrder = 0;
+ for (McQuestionDTO questionDTO : questionDTOs) {
+ String currentQuestionText = questionDTO.getQuestion();
+
+ // skip empty questions
+ if (currentQuestionText.isEmpty()) {
+ continue;
+ }
+
+ ++displayOrder;
+ String currentFeedback = questionDTO.getFeedback();
+ String currentMark = questionDTO.getMark();
+ /* set the default mark in case it is not provided */
+ if (currentMark == null) {
+ currentMark = "1";
+ }
+
+ McQueContent question = getQuestionByUid(questionDTO.getUid());
+
+ // in case question doesn't exist
+ if (question == null) {
+ question = new McQueContent(currentQuestionText, new Integer(displayOrder), new Integer(currentMark),
+ currentFeedback, content, null, null);
+
+ // adding a new question to content
+ content.getMcQueContents().add(question);
+ question.setMcContent(content);
+
+ // in case question exists already
+ } else {
+
+ question.setQuestion(currentQuestionText);
+ question.setFeedback(currentFeedback);
+ question.setDisplayOrder(new Integer(displayOrder));
+ question.setMark(new Integer(currentMark));
+ }
+
+ // persist candidate answers
+ List optionDTOs = questionDTO.getOptionDtos();
+ Set oldOptions = question.getMcOptionsContents();
+ Set newOptions = new HashSet();
+ int displayOrderOption = 1;
+ for (McOptionDTO optionDTO : optionDTOs) {
+
+ Long optionUid = optionDTO.getUid();
+ String optionText = optionDTO.getCandidateAnswer();
+ boolean isCorrectOption = "Correct".equals(optionDTO.getCorrect());
+
+ //find persisted option if it exists
+ McOptsContent option = new McOptsContent();
+ for (McOptsContent oldOption : oldOptions) {
+ if (oldOption.getUid().equals(optionUid)) {
+ option = oldOption;
+ }
+ }
+
+ option.setDisplayOrder(displayOrderOption);
+ option.setCorrectOption(isCorrectOption);
+ option.setMcQueOptionText(optionText);
+ option.setMcQueContent(question);
+
+ newOptions.add(option);
+ displayOrderOption++;
+ }
+
+ question.setMcOptionsContents(newOptions);
+
+ // updating the existing question content
+ updateQuestion(question);
+
+ }
+ return content;
+ }
+
+ @Override
+ public void releaseQuestionsFromCache(McContent content) {
+ for (McQueContent question : (Set) content.getMcQueContents()) {
+ mcQueContentDAO.releaseQuestionFromCache(question);
+ }
+ }
+
+ @Override
+ public McQueUsr createMcUser(Long toolSessionID) throws McApplicationException {
+ try {
+ HttpSession ss = SessionManager.getSession();
+ UserDTO toolUser = (UserDTO) ss.getAttribute(AttributeNames.USER);
+ Long userId = toolUser.getUserID().longValue();
+ String userName = toolUser.getLogin();
+ String fullName = toolUser.getFirstName() + " " + toolUser.getLastName();
+ McSession mcSession = getMcSessionById(toolSessionID.longValue());
+
+ McQueUsr user = new McQueUsr(userId, userName, fullName, mcSession, new TreeSet());
+ mcUserDAO.saveMcUser(user);
+
+ return user;
+ } catch (DataAccessException e) {
+ throw new McApplicationException("Exception occured when lams is creating mc QueUsr: " + e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public void updateMcQueUsr(McQueUsr mcQueUsr) throws McApplicationException {
+ try {
+ mcUserDAO.updateMcUser(mcQueUsr);
+ } catch (DataAccessException e) {
+ throw new McApplicationException("Exception occured when lams is updating mc QueUsr: " + e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public McQueUsr getMcUserBySession(final Long queUsrId, final Long mcSessionUid) throws McApplicationException {
+ try {
+ return mcUserDAO.getMcUserBySession(queUsrId, mcSessionUid);
+ } catch (DataAccessException e) {
+ throw new McApplicationException("Exception occured when lams is getting mc QueUsr: " + e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public McQueUsr getMcUserByUID(Long uid) throws McApplicationException {
+ try {
+ return mcUserDAO.getMcUserByUID(uid);
+ } catch (DataAccessException e) {
+ throw new McApplicationException(
+ "Exception occured when lams is getting the mc QueUsr by uid." + e.getMessage(), e);
+ }
+ }
+
+ @Override
+ public List