private void loginUser(String ipAddress, User user) { Session sess = SessionManager.getCurrentSession(); UsageSessionService.login( user.getId(), user.getEid(), ipAddress, null, UsageSessionService.EVENT_LOGIN_WS); sess.setUserId(user.getId()); sess.setUserEid(user.getEid()); }
// Returns getUser and getUserByEid on the input string // @return Either the id of the user, or the same string if not defined private String getUserDefined(String usr) { // Set the original user id String userId = usr; User userinfo; try { userinfo = UserDirectoryService.getUser(usr); userId = userinfo.getId(); if (LOG.isDebugEnabled()) { LOG.debug("getUserDefined: username for " + usr + " is " + userId); } return userId; } catch (UserNotDefinedException e) { try { // try with the user eid userinfo = UserDirectoryService.getUserByEid(usr); userId = userinfo.getId(); } catch (UserNotDefinedException ee) { // This is mostly expected behavior, don't need to notify about it, the UI can handle it if (LOG.isDebugEnabled()) { LOG.debug("getUserDefined: User Not Defined" + userId); } } } return userId; }
/** {@inheritDoc} */ public boolean canViewAllPurposeItem(Assignment a) { boolean rv = false; if (a != null) { AssignmentAllPurposeItem aItem = getAllPurposeItem(a.getId()); if (aItem != null) { if (!aItem.getHide()) { Time now = TimeService.newTime(); Date releaseDate = aItem.getReleaseDate(); Date retractDate = aItem.getRetractDate(); if (releaseDate == null && retractDate == null) { // no time limitation on showing the item rv = true; } else if (releaseDate != null && retractDate == null) { // has relase date but not retract date rv = now.getTime() > releaseDate.getTime(); } else if (releaseDate == null && retractDate != null) { // has retract date but not release date rv = now.getTime() < retractDate.getTime(); } else if (now != null) { // both releaseDate and retract date are not null // has both release and retract dates rv = now.getTime() > releaseDate.getTime() && now.getTime() < retractDate.getTime(); } } else { rv = false; } } if (rv) { // reset rv rv = false; // need to check role/user permission only if the above time test returns true List<String> access = getAccessListForAllPurposeItem(aItem); User u = m_userDirectoryService.getCurrentUser(); if (u != null) { if (access.contains(u.getId())) rv = true; else { try { String role = m_authzGroupService.getUserRole( u.getId(), m_siteService.siteReference(a.getContext())); if (access.contains(role)) rv = true; } catch (Exception e) { Log.warn( this + ".callViewAllPurposeItem() Hibernate cannot access user role for user id= " + u.getId()); return rv; } } } } } return rv; }
private User addUserWithEid(String eid) throws Exception { User user = userDirectoryService.addUser( null, eid, FIRST_NAME, eid, eid + "@somewhere.edu", eid + "pwd", "Guest", null); log.debug("addUser eid=" + eid + ", id=" + user.getId()); return user; }
/** @see junit.framework.TestCase#setUp() */ @Before public void setUp() throws Exception { super.setUp(); trustedLoginFilter = new TrustedLoginFilter(); when(componentManager.get(ServerConfigurationService.class)) .thenReturn(serverConfigurationService); when(componentManager.get(SessionManager.class)).thenReturn(sessionManager); when(componentManager.get(UserDirectoryService.class)).thenReturn(userDirectoryService); when(serverConfigurationService.getBoolean( TrustedLoginFilter.ORG_SAKAIPROJECT_UTIL_TRUSTED_LOGIN_FILTER_ENABLED, true)) .thenReturn(true); when(serverConfigurationService.getString( TrustedLoginFilter.ORG_SAKAIPROJECT_UTIL_TRUSTED_LOGIN_FILTER_SHARED_SECRET, null)) .thenReturn("e2KS54H35j6vS5Z38nK40"); when(serverConfigurationService.getString( TrustedLoginFilter.ORG_SAKAIPROJECT_UTIL_TRUSTED_LOGIN_FILTER_SAFE_HOSTS, trustedLoginFilter.safeHosts)) .thenReturn(trustedLoginFilter.safeHosts); when(request.getRemoteHost()).thenReturn("localhost"); when(request.getHeader("x-sakai-token")) .thenReturn("sw9TTTqlEbGQkELqQuQPq92ydr4=;username;nonce"); // default to non-existing session to exercise more code when(existingSession.getUserEid()).thenReturn(null); when(sessionManager.getCurrentSession()).thenReturn(existingSession); when(sessionManager.startSession()).thenReturn(newSession); when(user.getEid()).thenReturn("username"); when(user.getId()).thenReturn("uuid1234567890"); when(userDirectoryService.getUserByEid("username")).thenReturn(user); trustedLoginFilter.setupTestCase(componentManager); trustedLoginFilter.init(config); }
/** @inheritDoc */ public List getUnassignedMembersInRole(final String siteContext, final Role role) { List siteMembers = getSiteMembersInRole(siteContext, role); // Get all userUids of all users in sections List<String> sectionedUserUids = new ArrayList<String>(); List sections = getSections(siteContext); for (Iterator sectionIter = sections.iterator(); sectionIter.hasNext(); ) { CourseSection section = (CourseSection) sectionIter.next(); List sectionUsers = securityService.unlockUsers(getLock(role), section.getUuid()); for (Iterator userIter = sectionUsers.iterator(); userIter.hasNext(); ) { org.sakaiproject.user.api.User user = (org.sakaiproject.user.api.User) userIter.next(); sectionedUserUids.add(user.getId()); } } // Now generate the list of unsectioned enrollments by subtracting the two collections // Since the APIs return different kinds of objects, we need to iterate List<ParticipationRecord> unsectionedMembers = new ArrayList<ParticipationRecord>(); for (Iterator iter = siteMembers.iterator(); iter.hasNext(); ) { ParticipationRecord record = (ParticipationRecord) iter.next(); if (!sectionedUserUids.contains(record.getUser().getUserUid())) { unsectionedMembers.add(record); } } return unsectionedMembers; }
/** {@inheritDoc} */ public boolean canEditNoteItem(Assignment a) { String userId = ""; User u = m_userDirectoryService.getCurrentUser(); if (u != null) { userId = u.getId(); } if (a != null) { AssignmentNoteItem note = getNoteItem(a.getId()); if (note != null) { if (note.getCreatorId().equals(userId)) { // being creator can edit return true; } else if (note.getShareWith() == AssignmentConstants.NOTE_READ_AND_WRITE_BY_OTHER && m_assignmentService.allowGradeSubmission(a.getReference())) { return true; } } else { return true; } } else { return true; } return false; }
/** {@inheritDoc} */ public boolean canReadNoteItem(Assignment a, String context) { if (a != null) { AssignmentNoteItem note = getNoteItem(a.getId()); if (note != null) { User u = m_userDirectoryService.getCurrentUser(); String noteCreatorId = note.getCreatorId(); if (noteCreatorId.equals(u.getId())) { return true; } else if (m_assignmentService.allowGradeSubmission(a.getReference())) { // check whether the instructor type can view the note int share = note.getShareWith(); if (share == AssignmentConstants.NOTE_READ_BY_OTHER || share == AssignmentConstants.NOTE_READ_AND_WRITE_BY_OTHER) { return true; } } } } else { if (m_assignmentService.allowAddAssignment(context)) { return true; } } return false; }
protected String getUserId(User u) { User user = getUser(u); if (user == null) return ""; String id = user.getId(); if (id == null) return ""; return id; }
/** {@inheritDoc} */ public void notifyCourseRequestRequester( String requestEmail, String supportEmailContent, String termTitle) { User currentUser = userDirectoryService.getCurrentUser(); String currentUserDisplayName = currentUser != null ? currentUser.getDisplayName() : ""; String currentUserDisplayId = currentUser != null ? currentUser.getDisplayId() : ""; String currentUserId = currentUser != null ? currentUser.getId() : ""; String currentUserEmail = currentUser != null ? currentUser.getEmail() : ""; ResourceLoader rb = new ResourceLoader(currentUserId, "UserNotificationProvider"); String from = requestEmail; String to = currentUserEmail; String headerTo = to; String replyTo = to; // message subject String message_subject = rb.getString("java.sitereqfrom") + " " + currentUserDisplayName + " " + rb.getString("java.for") + " " + termTitle; StringBuffer buf = new StringBuffer(); buf.append(rb.getString("java.isbeing") + " "); buf.append(rb.getString("java.meantime") + "\n\n"); buf.append(rb.getString("java.copy") + "\n\n"); buf.append(supportEmailContent); buf.append("\n" + rb.getString("java.wish") + " " + requestEmail); emailService.send(from, to, message_subject, buf.toString(), headerTo, replyTo, null); }
/** @return return the current user */ public EmailUser getCurrentUser() { EmailUser euser = null; User curU = null; try { curU = m_userDirectoryService.getCurrentUser(); euser = new EmailUser(curU.getId(), curU.getDisplayName(), curU.getEmail()); } catch (Exception e) { log.debug("Exception: Mailtool.getCurrentUser(), " + e.getMessage()); } return euser; }
/** * Refine the recipients list to only users that are actually members of the given site. * * @param users The list of users to refine * @param site The site whose membership the users will be refined to */ protected void refineToSiteMembers(List<User> users, Site site) { Set<Member> members = site.getMembers(); Set<String> memberUserIds = getUserIds(members); for (Iterator<User> i = users.listIterator(); i.hasNext(); ) { User user = i.next(); if (!memberUserIds.contains(user.getId())) { i.remove(); } } }
/** * Creates a searchBean * * @param request The HTTP request * @param searchService The search service to use * @param siteService the site service * @param portalService the portal service * @throws IdUnusedException if there is no current worksite */ public SearchBeanImpl( HttpServletRequest request, SearchService searchService, SiteService siteService, ToolManager toolManager, UserDirectoryService userDirectoryService, SecurityService securityService, ServerConfigurationService serverConfigurationService) throws IdUnusedException { this.search = request.getParameter(SEARCH_PARAM); this.searchService = searchService; this.siteService = siteService; this.toolManager = toolManager; this.placementId = this.toolManager.getCurrentPlacement().getId(); this.toolId = this.toolManager.getCurrentTool().getId(); this.siteId = this.toolManager.getCurrentPlacement().getContext(); this.serverConfigurationService = serverConfigurationService; this.securityService = securityService; try { this.requestPage = Integer.parseInt(request.getParameter(SEARCH_PAGE)); } catch (Exception ex) { log.debug(ex); } currentSite = this.siteService.getSite(this.siteId); try { this.scope = Scope.valueOf(request.getParameter(SEARCH_SCOPE)); } catch (NullPointerException npe) { } catch (IllegalArgumentException iae) { log.debug(iae); log.warn("Invalid Scope Supplied: " + request.getParameter(SEARCH_SCOPE)); } User user = userDirectoryService.getCurrentUser(); if (user != null) currentUser = user.getId(); requestURL = request.getRequestURL().toString(); // normal or pda portal? checkPdaPortal(request); }
/** {@inheritDoc} */ public void notifyNewUserEmail(User user, String newUserPassword, Site site) { ResourceLoader rb = new ResourceLoader("UserNotificationProvider"); // set the locale to individual receipient's setting rb.setContextLocale(rb.getLocale(user.getId())); String from = getSetupRequestEmailAddress(); String productionSiteName = serverConfigurationService.getString("ui.service", ""); String productionSiteUrl = serverConfigurationService.getPortalUrl(); String newUserEmail = user.getEmail(); String to = newUserEmail; String headerTo = newUserEmail; // UVa: change Reply-To to be the From (collab support) address String replyTo = from; String message_subject = productionSiteName + " " + rb.getString("java.newusernoti"); String content = ""; if (from != null && newUserEmail != null) { StringBuilder buf = new StringBuilder(); buf.setLength(0); // email body buf.append(user.getDisplayName() + ":\n\n"); buf.append( rb.getString("java.addedto") + " " + productionSiteName + " (" + productionSiteUrl + ") "); buf.append(rb.getString("java.simpleby") + " "); buf.append(userDirectoryService.getCurrentUser().getDisplayName() + ". \n\n"); buf.append(rb.getString("java.passwordis1") + "\n" + newUserPassword + "\n\n"); buf.append(rb.getString("java.passwordis2") + "\n\n"); content = buf.toString(); emailService.send(from, to, message_subject, content, headerTo, replyTo, null); } }
private String addOrCreateTool(Map payload, boolean trustedConsumer, User user, Site site) throws LTIException { // Check if the site already has the tool String toolPlacementId = null; String tool_id = (String) payload.get("tool_id"); try { site = SiteService.getSite(site.getId()); ToolConfiguration toolConfig = site.getToolForCommonId(tool_id); if (toolConfig != null) { toolPlacementId = toolConfig.getId(); } } catch (Exception e) { M_log.warn(e.getLocalizedMessage(), e); throw new LTIException("launch.tool.search", "tool_id=" + tool_id, e); } if (M_log.isDebugEnabled()) { M_log.debug("toolPlacementId=" + toolPlacementId); } // If tool not in site, and we are a trusted consumer, error // Otherwise, add tool to the site ToolConfiguration toolConfig = null; if (BasicLTIUtil.isBlank(toolPlacementId)) { try { SitePage sitePageEdit = null; sitePageEdit = site.addPage(); sitePageEdit.setTitle(tool_id); toolConfig = sitePageEdit.addTool(); toolConfig.setTool(tool_id, ToolManager.getTool(tool_id)); toolConfig.setTitle(tool_id); Properties propsedit = toolConfig.getPlacementConfig(); propsedit.setProperty( BASICLTI_RESOURCE_LINK, (String) payload.get(BasicLTIConstants.RESOURCE_LINK_ID)); pushAdvisor(); try { SiteService.save(site); M_log.info("Tool added, tool_id=" + tool_id + ", siteId=" + site.getId()); } catch (Exception e) { throw new LTIException( "launch.site.save", "tool_id=" + tool_id + ", siteId=" + site.getId(), e); } finally { popAdvisor(); } toolPlacementId = toolConfig.getId(); } catch (Exception e) { throw new LTIException( "launch.tool.add", "tool_id=" + tool_id + ", siteId=" + site.getId(), e); } } // Get ToolConfiguration for tool if not already setup if (toolConfig == null) { toolConfig = site.getToolForCommonId(tool_id); } // Check user has access to this tool in this site if (!ToolManager.isVisible(site, toolConfig)) { M_log.warn( "Not allowed to access tool user_id=" + user.getId() + " site=" + site.getId() + " tool=" + tool_id); throw new LTIException( "launch.site.tool.denied", "user_id=" + user.getId() + " site=" + site.getId() + " tool=" + tool_id, null); } return toolPlacementId; }
/** * Process that archives the sites * * @param sites list of SparseSite * @throws InterruptedException */ private void archiveSites( List<SparseSite> sites, String selectedTerm, Session currentSession, User currentUser) throws InterruptedException { if (isLocked()) { throw new IllegalStateException( "Cannot run batch archive, an archive job is already in progress"); } batchArchiveStarted = System.currentTimeMillis(); batchArchiveMessage = rb.getFormattedMessage( "archive.batch.term.text.statusmessage.start", new Object[] {sites.size(), selectedTerm, 0}); batchArchiveStatus = "RUNNING"; log.info( "Batch archive started for term: " + selectedTerm + ". Archiving " + sites.size() + " sites."); Session threadSession = sessionManager.getCurrentSession(); if (threadSession == null) { threadSession = sessionManager.startSession(); } threadSession.setUserId(currentUser.getId()); threadSession.setActive(); sessionManager.setCurrentSession(threadSession); authzGroupService.refreshUser(currentUser.getId()); // counters so we can run this in batches if we have a number of sites to process int archiveCount = 0; try { for (SparseSite s : sites) { log.info("Processing site: " + s.getTitle()); // archive the site archiveService.archive(s.getId()); // compress it // TODO check return value? do we care? try { archiveService.archiveAndZip(s.getId()); } catch (IOException e) { e.printStackTrace(); } archiveCount++; // update message if (archiveCount % 1 == 0) { int percentComplete = (int) (archiveCount * 100) / sites.size(); batchArchiveMessage = rb.getFormattedMessage( "archive.batch.term.text.statusmessage.update", new Object[] {sites.size(), selectedTerm, archiveCount, percentComplete}); } // sleep if we need to and keep sessions alive if (archiveCount > 0 && archiveCount % NUM_SITES_PER_BATCH == 0) { log.info("Sleeping for " + PAUSE_TIME_MS + "ms"); Thread.sleep(PAUSE_TIME_MS); threadSession.setActive(); currentSession.setActive(); } // check timeout if (!isLocked()) { throw new RuntimeException("Timeout occurred while running batch archive"); } } // complete batchArchiveMessage = rb.getFormattedMessage( "archive.batch.term.text.statusmessage.complete", new Object[] {sites.size(), selectedTerm}); log.info("Batch archive complete."); } finally { // reset batchArchiveStatus = STATUS_COMPLETE; batchArchiveStarted = 0; threadSession.clear(); threadSession.invalidate(); } }
/** {@inheritDoc} */ public void notifyAddedParticipant(boolean newNonOfficialAccount, User user, Site site) { ResourceLoader rb = new ResourceLoader(user.getId(), "UserNotificationProvider"); String from = serverConfigurationService.getBoolean(NOTIFY_FROM_CURRENT_USER, false) ? getCurrentUserEmailAddress() : getSetupRequestEmailAddress(); if (from != null) { String productionSiteName = serverConfigurationService.getString("ui.service", ""); String productionSiteUrl = serverConfigurationService.getPortalUrl(); String nonOfficialAccountUrl = serverConfigurationService.getString("nonOfficialAccount.url", null); String emailId = user.getEmail(); String to = emailId; String headerTo = emailId; // UVa: change Reply-To to be the user adding the new participant String replyTo = from; String message_subject = productionSiteName + " " + rb.getString("java.sitenoti"); String content = ""; StringBuilder buf = new StringBuilder(); buf.setLength(0); // email bnonOfficialAccounteen newly added nonOfficialAccount account // and other users buf.append(user.getDisplayName() + ":\n\n"); buf.append( rb.getString("java.following") + " " + productionSiteName + " " + rb.getString("java.simplesite") + "\n"); buf.append(site.getTitle() + "\n"); buf.append(rb.getString("java.simpleby") + " "); buf.append(userDirectoryService.getCurrentUser().getDisplayName() + ". \n\n"); if (newNonOfficialAccount) { buf.append(serverConfigurationService.getString("nonOfficialAccountInstru", "") + "\n"); if (nonOfficialAccountUrl != null) { buf.append(rb.getString("java.togeta1") + "\n" + nonOfficialAccountUrl + "\n"); buf.append(rb.getString("java.togeta2") + "\n\n"); } buf.append(rb.getString("java.once") + " " + productionSiteName + ": \n"); buf.append( rb.getString("java.loginhow1") + " " + productionSiteName + ": " + productionSiteUrl + "\n"); buf.append(rb.getString("java.loginhow2") + "\n"); buf.append(rb.getString("java.loginhow3") + "\n"); } else { buf.append(rb.getString("java.tolog") + "\n"); buf.append( rb.getString("java.loginhow1") + " " + productionSiteName + ": " + productionSiteUrl + "\n"); buf.append(rb.getString("java.loginhow2") + "\n"); buf.append(rb.getString("java.loginhow3u") + "\n"); } buf.append(rb.getString("java.tabscreen")); content = buf.toString(); emailService.send(from, to, message_subject, content, headerTo, replyTo, null); } // if }
@WebMethod @Path("/setAssignmentGradeCommentforUser") @Produces("text/plain") @GET public String setAssignmentGradeCommentforUser( @WebParam(name = "sessionId", partName = "sessionId") @QueryParam("sessionId") String sessionId, @WebParam(name = "assignmentId", partName = "assignmentId") @QueryParam("assignmentId") String assignmentId, @WebParam(name = "userId", partName = "userId") @QueryParam("userId") String userId, @WebParam(name = "comment", partName = "comment") @QueryParam("comment") String comment, @WebParam(name = "grade", partName = "grade") @QueryParam("grade") String grade) { // establish the session try { Session s = establishSession(sessionId); LOG.info( "User " + s.getUserEid() + " setting assignment grade/comment for " + userId + " on " + assignmentId + " to " + grade); User user = userDirectoryService.getUserByEid(userId); if (user == null) { return "user does not exist"; } Assignment assign = assignmentService.getAssignment(assignmentId); String aReference = assign.getReference(); if (!securityService.unlock( AssignmentService.SECURE_GRADE_ASSIGNMENT_SUBMISSION, aReference)) { LOG.warn("User " + s.getUserEid() + " does not have permission to set assignment grades"); return "failure: no permission"; } LOG.info( "Setting assignment grade/comment for " + userId + " on " + assignmentId + " to " + grade); AssignmentSubmission sub = assignmentService.getSubmission(assignmentId, user); AssignmentSubmissionEdit asEdit = null; String context = assign.getContext(); if (sub == null) { asEdit = assignmentService.addSubmission(context, assignmentId, user.getId()); } else { asEdit = assignmentService.editSubmission(sub.getReference()); } asEdit.setFeedbackComment(comment); asEdit.setGrade(grade); asEdit.setGraded(true); asEdit.setGradeReleased(true); assignmentService.commitEdit(asEdit); // If necessary, update the assignment grade in the Gradebook String sReference = asEdit.getReference(); String associateGradebookAssignment = StringUtils.trimToNull( assign .getProperties() .getProperty(AssignmentService.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT)); // update grade in gradebook integrateGradebook( aReference, associateGradebookAssignment, null, null, -1, null, sReference, "update", context); } catch (Exception e) { LOG.error( "WS setAssignmentGradeCommentforUser(): Exception while setting assignment grade/comment for " + userId + " on " + assignmentId + " to " + grade, e); return e.getClass().getName() + " : " + e.getMessage(); } return "success"; }
/* * (non-Javadoc) * * @see org.sakaiproject.authz.api.SecurityService#unlock(org.sakaiproject.user.api.User, * java.lang.String, java.lang.String) */ public boolean unlock(User user, String lock, String reference) { return unlock(user.getId(), lock, reference); }
/** Method called by the scheduledInvocationManager */ public void execute(String opaqueContext) { try { // for group assignments, we need to have a user ID, otherwise, an exception is thrown: sessionManager.getCurrentSession().setUserEid("admin"); sessionManager.getCurrentSession().setUserId("admin"); Assignment assignment = assignmentService.getAssignment(opaqueContext); if (assignment.getAllowPeerAssessment() && !assignment.getDraft()) { int numOfReviews = assignment.getPeerAssessmentNumReviews(); List<AssignmentSubmission> submissions = (List<AssignmentSubmission>) assignmentService.getSubmissions(assignment); // keep a map of submission ids to look up possible existing peer assessments Map<String, AssignmentSubmission> submissionIdMap = new HashMap<String, AssignmentSubmission>(); // keep track of who has been assigned an assessment Map<String, Map<String, PeerAssessmentItem>> assignedAssessmentsMap = new HashMap<String, Map<String, PeerAssessmentItem>>(); // keep track of how many assessor's each student has Map<String, Integer> studentAssessorsMap = new HashMap<String, Integer>(); List<User> submitterUsersList = (List<User>) assignmentService.allowAddSubmissionUsers(assignment.getReference()); List<String> submitterIdsList = new ArrayList<String>(); if (submitterUsersList != null) { for (User u : submitterUsersList) { submitterIdsList.add(u.getId()); } } // loop through the assignment submissions and setup the maps and lists for (AssignmentSubmission s : submissions) { if (s.getTimeSubmitted() != null // check if the submission is submitted, if not, see if there is any submission data // to review (i.e. draft was auto submitted) && (s.getSubmitted() || ((s.getSubmittedText() != null && !"".equals(s.getSubmittedText().trim()) || (s.getSubmittedAttachments() != null && s.getSubmittedAttachments().size() > 0)))) && submitterIdsList.contains(s.getSubmitterId()) && !"admin".equals(s.getSubmitterId())) { // only deal with users in the submitter's list submissionIdMap.put(s.getId(), s); assignedAssessmentsMap.put( s.getSubmitterId(), new HashMap<String, PeerAssessmentItem>()); studentAssessorsMap.put(s.getSubmitterId(), 0); } } // this could be an update to an existing assessment... just make sure to grab any existing // review items first List<PeerAssessmentItem> existingItems = getPeerAssessmentItems(submissionIdMap.keySet(), assignment.getContent().getFactor()); List<PeerAssessmentItem> removeItems = new ArrayList<PeerAssessmentItem>(); // remove all empty items to start from scratch: for (Iterator iterator = existingItems.iterator(); iterator.hasNext(); ) { PeerAssessmentItem peerAssessmentItem = (PeerAssessmentItem) iterator.next(); if (peerAssessmentItem.getScore() == null && (peerAssessmentItem.getComment() == null || "".equals(peerAssessmentItem.getComment().trim()))) { removeItems.add(peerAssessmentItem); iterator.remove(); } } if (removeItems.size() > 0) { getHibernateTemplate().deleteAll(removeItems); } // loop through the items and update the map values: for (PeerAssessmentItem p : existingItems) { if (submissionIdMap.containsKey(p.getSubmissionId())) { // first, add this assessment to the AssignedAssessmentsMap AssignmentSubmission s = submissionIdMap.get(p.getSubmissionId()); // Next, increment the count for studentAssessorsMap Integer count = studentAssessorsMap.get(s.getSubmitterId()); if (count == null) { // probably not possible, just check count = 0; } // check if the count is less than num of reviews before added another one, // otherwise, we need to delete this one (if it's empty) if (count < numOfReviews || p.getScore() != null || p.getComment() != null) { count++; studentAssessorsMap.put(s.getSubmitterId(), count); Map<String, PeerAssessmentItem> peerAssessments = assignedAssessmentsMap.get(p.getAssessorUserId()); if (peerAssessments == null) { // probably not possible, but just check peerAssessments = new HashMap<String, PeerAssessmentItem>(); } peerAssessments.put(p.getSubmissionId(), p); assignedAssessmentsMap.put(p.getAssessorUserId(), peerAssessments); } else { // this shoudln't happen since the code above removes all empty assessments, but just // in case: getHibernateTemplate().delete(p); } } else { // this isn't realy possible since we looked up the peer assessments by submission id log.error( "AssignmentPeerAssessmentServiceImpl: found a peer assessment with an invalid session id: " + p.getSubmissionId()); } } // ok now that we have any existing assigned reviews accounted for, let's make sure that the // number of reviews is setup properly, // if not, add some // let's get a random order of submission IDs so we can have a random assigning algorithm List<String> randomSubmissionIds = new ArrayList<String>(submissionIdMap.keySet()); Collections.shuffle(randomSubmissionIds); List<PeerAssessmentItem> newItems = new ArrayList<PeerAssessmentItem>(); int i = 0; for (String submissionId : randomSubmissionIds) { AssignmentSubmission s = submissionIdMap.get(submissionId); // first find out how many existing items exist for this user: Integer assignedCount = studentAssessorsMap.get(s.getSubmitterId()); // by creating a tailing list (snake style), we eliminate the issue where you can be stuck // with // a submission and the same submission user left, making for uneven distributions of // submission reviews List<String> snakeSubmissionList = new ArrayList<String>(randomSubmissionIds.subList(i, randomSubmissionIds.size())); if (i > 0) { snakeSubmissionList.addAll(new ArrayList<String>(randomSubmissionIds.subList(0, i))); } while (assignedCount < numOfReviews) { // we need to add more reviewers for this user's submission String lowestAssignedAssessor = findLowestAssignedAssessor( assignedAssessmentsMap, s.getSubmitterId(), submissionId, snakeSubmissionList, submissionIdMap); if (lowestAssignedAssessor != null) { Map<String, PeerAssessmentItem> assessorsAssessmentMap = assignedAssessmentsMap.get(lowestAssignedAssessor); if (assessorsAssessmentMap == null) { assessorsAssessmentMap = new HashMap<String, PeerAssessmentItem>(); } PeerAssessmentItem newItem = new PeerAssessmentItem(); newItem.setAssessorUserId(lowestAssignedAssessor); newItem.setSubmissionId(submissionId); newItem.setAssignmentId(assignment.getId()); newItems.add(newItem); assessorsAssessmentMap.put(submissionId, newItem); assignedAssessmentsMap.put(lowestAssignedAssessor, assessorsAssessmentMap); // update this submission user's count: assignedCount++; studentAssessorsMap.put(submissionId, assignedCount); } else { break; } } i++; } if (newItems.size() > 0) { getHibernateTemplate().saveOrUpdateAll(newItems); } } } catch (IdUnusedException e) { log.error(e.getMessage(), e); } catch (PermissionException e) { log.error(e.getMessage(), e); } finally { sessionManager.getCurrentSession().setUserEid(null); sessionManager.getCurrentSession().setUserId(null); } }
@SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ipAddress = request.getRemoteAddr(); if (M_log.isDebugEnabled()) { M_log.debug("Basic LTI Provider request from IP=" + ipAddress); } String enabled = ServerConfigurationService.getString("basiclti.provider.enabled", null); if (enabled == null || !("true".equals(enabled))) { M_log.warn("Basic LTI Provider is Disabled IP=" + ipAddress); response.sendError(HttpServletResponse.SC_FORBIDDEN, "Basic LTI Provider is Disabled"); return; } if ("/casa.json".equals(request.getPathInfo())) { if (ServerConfigurationService.getBoolean("casa.provider.enabled", true)) { handleCASAList(request, response); return; } else { M_log.warn("CASA Provider is Disabled IP=" + ipAddress); response.sendError(HttpServletResponse.SC_FORBIDDEN, "CASA Provider is Disabled"); return; } } if ("/canvas-config.xml".equals(request.getPathInfo())) { if (ServerConfigurationService.getBoolean("canvas.config.enabled", true)) { handleCanvasConfig(request, response); return; } else { M_log.warn("Canvas config is Disabled IP=" + ipAddress); response.sendError(HttpServletResponse.SC_FORBIDDEN, "Canvas config is Disabled"); return; } } // If this is a LTI request of any kind, make sure we don't have any // prior payload in the session. if (BasicLTIUtil.isRequest(request)) { Session sess = SessionManager.getCurrentSession(); sess.removeAttribute("payload"); } // Check if we support ContentItem. // If we are doing ContentItem and have a payload and are not a launch // short-circuit to ContentItem if ("/content.item".equals(request.getPathInfo())) { if (!ServerConfigurationService.getBoolean("contentitem.provider", true)) { M_log.warn("ContentItem is Disabled IP=" + ipAddress); response.sendError(HttpServletResponse.SC_FORBIDDEN, "ContentItem is Disabled"); return; } else { Session sess = SessionManager.getCurrentSession(); Map session_payload = (Map) sess.getAttribute("payload"); if (session_payload != null) { // Post-Login requests to content.item M_log.debug("ContentItem already logged in " + sess.getUserId()); handleContentItem(request, response, session_payload); return; } } } if (M_log.isDebugEnabled()) { Map<String, String[]> params = (Map<String, String[]>) request.getParameterMap(); for (Map.Entry<String, String[]> param : params.entrySet()) { M_log.debug(param.getKey() + ":" + param.getValue()[0]); } } Map payload = getPayloadAsMap(request); // Get the list of highly trusted consumers from sakai.properties. // If the incoming consumer is highly trusted, we use the context_id and // site_id as is, // ie without prefixing them with the oauth_consumer_key first. // We also don't both checking their roles in the site. boolean isTrustedConsumer = BasicLTIProviderUtil.isHighlyTrustedConsumer(payload); /* * Get the list of email trusted consumers from sakai.properties. If the * incoming consumer is email trusted, we use the email address provided * by the consumer and look up the "user" info from sakai instead of * consumer's. This use case is especially valuable if 2 different LMS's * acting as TP and TC referring to same user and can be uniquely * identified by email address. more details SAK-29372 */ boolean isEmailTrustedConsumer = BasicLTIProviderUtil.isEmailTrustedConsumer(payload); /* * Checking if the email trusted consumer property and trusted consumer * and not both enabled. the case would be an error condition */ if (isTrustedConsumer && isEmailTrustedConsumer) { M_log.warn( "Both Email Trusted and Trusted Consumer property is enabled, this is invalid IP=" + ipAddress); response.sendError( HttpServletResponse.SC_FORBIDDEN, "Both Email Trusted and Trusted Consumer property is enabled, this is invalid "); return; } try { invokeProcessors(payload, isTrustedConsumer, ProcessingState.beforeValidation); validate(payload, isTrustedConsumer); invokeProcessors(payload, isTrustedConsumer, ProcessingState.afterValidation); User user = userFinderOrCreator.findOrCreateUser(payload, isTrustedConsumer, isEmailTrustedConsumer); invokeProcessors(payload, isTrustedConsumer, ProcessingState.afterUserCreation, user); // Check if we are loop-backing on the same server, and already logged in as same user Session sess = SessionManager.getCurrentSession(); String serverUrl = SakaiBLTIUtil.getOurServerUrl(); String ext_sakai_server = (String) payload.get("ext_sakai_server"); if ("/content.item".equals(request.getPathInfo()) && isTrustedConsumer && ext_sakai_server != null && ext_sakai_server.equals(serverUrl) && user.getId().equals(sess.getUserId())) { M_log.debug("ContentItem looping back as " + sess.getUserId()); sess.setAttribute("payload", payload); handleContentItem(request, response, payload); return; } loginUser(ipAddress, user); // Re-grab the session sess = SessionManager.getCurrentSession(); invokeProcessors(payload, isTrustedConsumer, ProcessingState.afterLogin, user); // This needs to happen after login, when we have a session for the user. userLocaleSetter.setupUserLocale(payload, user, isTrustedConsumer, isEmailTrustedConsumer); userPictureSetter.setupUserPicture(payload, user, isTrustedConsumer, isEmailTrustedConsumer); // The first launch of content.item - no site needed if ("/content.item".equals(request.getPathInfo())) { M_log.debug("ContentItem inital external login " + sess.getUserId()); sess.setAttribute("payload", payload); handleContentItem(request, response, payload); return; } Site site = findOrCreateSite(payload, isTrustedConsumer); invokeProcessors(payload, isTrustedConsumer, ProcessingState.afterSiteCreation, user, site); siteEmailPreferenceSetter.setupUserEmailPreferenceForSite( payload, user, site, isTrustedConsumer); site = siteMembershipUpdater.addOrUpdateSiteMembership(payload, isTrustedConsumer, user, site); invokeProcessors(payload, isTrustedConsumer, ProcessingState.afterSiteMembership, user, site); String toolPlacementId = addOrCreateTool(payload, isTrustedConsumer, user, site); invokeProcessors(payload, isTrustedConsumer, ProcessingState.beforeLaunch, user, site); syncSiteMembershipsOnceThenSchedule(payload, site, isTrustedConsumer, isEmailTrustedConsumer); // Construct a URL to this tool StringBuilder url = new StringBuilder(); url.append(SakaiBLTIUtil.getOurServerUrl()); url.append(ServerConfigurationService.getString("portalPath", "/portal")); url.append("/tool-reset/"); url.append(toolPlacementId); url.append("?panel=Main"); if (M_log.isDebugEnabled()) { M_log.debug("url=" + url.toString()); } // String toolLink = ServerConfigurationService.getPortalUrl()+ "/tool-reset/" + placement_id // + "?panel=Main"; // Compensate for bug in getPortalUrl() // toolLink = toolLink.replace("IMS BLTI Portlet", "portal"); response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_FOUND); response.sendRedirect(url.toString()); } catch (LTIException ltiException) { doError( request, response, ltiException.getErrorKey(), ltiException.getMessage(), ltiException.getCause()); } /* PrintWriter out = response.getWriter(); out.println("<body><div style=\"text-align: center\">"); out.println(" <br/> <br/> <br/> <br/>"); out.println(" <br/> <br/> <br/> <br/>"); out.println("<a href=\"" + url.toString() + "\">"); out.println("<span id=\"hideme\">" + rb.getString("launch.continue") + "</span>"); out.println("</a>"); out.println(" <script language=\"javascript\"> \n" + " document.getElementById(\"hideme\").style.display = \"none\";\n" + " location.href=\"" + url.toString() + "\";\n" + " </script> \n"); out.println("</div>"); out.println("</body>"); out.close(); */ }
protected boolean userIsAttendingTimeslot(User user, SignupTimeslot timeslot) { return timeslot.getAttendee(user.getId()) != null; }
public List /* EmailGroup */ getEmailGroupsByType(String roletypefilter) { List /* EmailGroup */ thegroups = new ArrayList(); List emailroles = this.getEmailRoles(); for (Iterator i = emailroles.iterator(); i.hasNext(); ) { EmailRole emailrole = (EmailRole) i.next(); if (emailrole.roletype.equals("role") && roletypefilter.equals("role")) { String realmid = emailrole.getRealmid(); AuthzGroup therealm = null; try { therealm = m_realmService.getAuthzGroup(realmid); } catch (GroupNotDefinedException e1) { log.debug("GroupNotDefinedException: Mailtool.getEmailGroups() #1, ", e1); return thegroups; } catch (Exception e2) { log.debug("Exception: Mailtool.getEmailGroups() #1, " + e2.getMessage()); return thegroups; } Set users = therealm.getUsersHasRole(emailrole.getRoleid()); List /* EmailUser */ mailusers = new ArrayList(); for (Iterator j = users.iterator(); j.hasNext(); ) { String userid = (String) j.next(); try { User theuser = m_userDirectoryService.getUser(userid); String firstname_for_display = ""; String lastname_for_display = ""; if (theuser.getFirstName().trim().equals("")) { if (theuser.getEmail().trim().equals("") && theuser.getLastName().trim().equals("")) firstname_for_display = theuser.getDisplayId(); // fix for SAK-7539 else firstname_for_display = theuser.getEmail(); // fix for SAK-7356 } else { firstname_for_display = theuser.getFirstName(); } lastname_for_display = theuser.getLastName(); EmailUser emailuser = new EmailUser( theuser.getId(), firstname_for_display, lastname_for_display, theuser.getEmail()); mailusers.add(emailuser); } catch (Exception e) { log.debug("Exception: OptionsBean.getEmailGroupsByType() #2, " + e.getMessage()); } } Collections.sort(mailusers); EmailGroup thegroup = new EmailGroup(emailrole, mailusers); thegroups.add(thegroup); } else if (emailrole.roletype.equals("group") && roletypefilter.equals("group")) { String sid = getSiteID(); Site currentSite = null; try { currentSite = siteService.getSite(sid); } catch (IdUnusedException e1) { log.debug("IdUnusedException: Mailtool.getEmailGroups() #3, ", e1); return thegroups; } catch (Exception e2) { log.debug("Exception: Mailtool.getEmailGroups() #3, " + e2.getMessage()); return thegroups; } Collection groups = currentSite.getGroups(); Group agroup = null; for (Iterator groupIterator = groups.iterator(); groupIterator.hasNext(); ) { agroup = (Group) groupIterator.next(); String groupname = agroup.getTitle(); if (emailrole.getRoleid().equals(groupname)) break; } Set users2 = agroup.getUsersHasRole(groupAwareRoleFound); List mailusers2 = new ArrayList(); for (Iterator k = users2.iterator(); k.hasNext(); ) { String userid2 = (String) k.next(); try { User theuser2 = m_userDirectoryService.getUser(userid2); String firstname_for_display = ""; String lastname_for_display = ""; if (theuser2.getFirstName().trim().equals("")) { if (theuser2.getEmail().trim().equals("") && theuser2.getLastName().trim().equals("")) firstname_for_display = theuser2.getDisplayId(); // fix for SAK-7539 else firstname_for_display = theuser2.getEmail(); // fix for SAK-7356 } else { firstname_for_display = theuser2.getFirstName(); } lastname_for_display = theuser2.getLastName(); EmailUser emailuser2 = new EmailUser( theuser2.getId(), firstname_for_display, lastname_for_display, theuser2.getEmail()); mailusers2.add(emailuser2); } catch (Exception e) { log.debug("Exception: OptionsBean.getEmailGroupsByType() #3-1, " + e.getMessage()); } } Collections.sort(mailusers2); EmailGroup thegroup2 = new EmailGroup(emailrole, mailusers2); thegroups.add(thegroup2); } // else else if (emailrole.roletype.equals("section") && roletypefilter.equals("section")) { String sid = getSiteID(); Site currentSite = null; try { currentSite = siteService.getSite(sid); } catch (IdUnusedException e1) { log.debug("IdUnusedException: Mailtool.getEmailGroups() #4, ", e1); return thegroups; } catch (Exception e2) { log.debug("Exception: Mailtool.getEmailGroups() #4, " + e2.getMessage()); return thegroups; } Collection groups = currentSite.getGroups(); Group agroup = null; for (Iterator groupIterator = groups.iterator(); groupIterator.hasNext(); ) { agroup = (Group) groupIterator.next(); String groupname = agroup.getTitle(); if (emailrole.getRoleid().equals(groupname)) break; } Set users2 = agroup.getUsersHasRole(groupAwareRoleFound); List mailusers2 = new ArrayList(); for (Iterator k = users2.iterator(); k.hasNext(); ) { String userid2 = (String) k.next(); try { User theuser2 = m_userDirectoryService.getUser(userid2); String firstname_for_display = ""; String lastname_for_display = ""; if (theuser2.getFirstName().trim().equals("")) { if (theuser2.getEmail().trim().equals("") && theuser2.getLastName().trim().equals("")) firstname_for_display = theuser2.getDisplayId(); // fix for SAK-7539 else firstname_for_display = theuser2.getEmail(); // fix for SAK-7356 } else { firstname_for_display = theuser2.getFirstName(); } lastname_for_display = theuser2.getLastName(); EmailUser emailuser2 = new EmailUser( theuser2.getId(), firstname_for_display, lastname_for_display, theuser2.getEmail()); mailusers2.add(emailuser2); } catch (Exception e) { log.debug("Exception: OptionsBean.getEmailGroupsByType() #4-1, " + e.getMessage()); } } Collections.sort(mailusers2); EmailGroup thegroup2 = new EmailGroup(emailrole, mailusers2); thegroups.add(thegroup2); } // else else if (emailrole.roletype.equals("role_groupaware") && roletypefilter.equals("role_groupaware")) { String realmid = emailrole.getRealmid(); AuthzGroup therealm = null; try { therealm = m_realmService.getAuthzGroup(realmid); } catch (GroupNotDefinedException e1) { log.debug("GroupNotDefinedException: Mailtool.getEmailGroupsByType() #5, ", e1); return thegroups; } catch (Exception e2) { log.debug("Exception: Mailtool.getEmailGroupsByType() #5, " + e2.getMessage()); return thegroups; } Set users = therealm.getUsersHasRole(emailrole.getRoleid()); List /* EmailUser */ mailusers = new ArrayList(); for (Iterator j = users.iterator(); j.hasNext(); ) { String userid = (String) j.next(); try { User theuser = m_userDirectoryService.getUser(userid); String firstname_for_display = ""; String lastname_for_display = ""; if (theuser.getFirstName().trim().equals("")) { if (theuser.getEmail().trim().equals("") && theuser.getLastName().trim().equals("")) firstname_for_display = theuser.getDisplayId(); // fix for SAK-7539 else firstname_for_display = theuser.getEmail(); // fix for SAK-7356 } else { firstname_for_display = theuser.getFirstName(); } lastname_for_display = theuser.getLastName(); EmailUser emailuser = new EmailUser( theuser.getId(), firstname_for_display, lastname_for_display, theuser.getEmail()); mailusers.add(emailuser); } catch (Exception e) { log.debug("Exception: OptionsBean.getEmailGroupsByType() #5-1, " + e.getMessage()); } } Collections.sort(mailusers); EmailGroup thegroup = new EmailGroup(emailrole, mailusers); thegroups.add(thegroup); } // else } return thegroups; }
/** {@inheritDoc} */ public void notifySiteCreation( Site site, List notifySites, boolean courseSite, String termTitle, String requestEmail) { // send emails String id = site.getId(); String title = site.getTitle(); SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance()); dform.applyPattern("yyyy-MM-dd HH:mm:ss"); String dateDisplay = dform.format(new Date()); User currentUser = userDirectoryService.getCurrentUser(); String currentUserName = currentUser.getDisplayName(); String currentUserId = currentUser.getId(); String currentUserEmail = currentUser.getEmail(); ResourceLoader rb = new ResourceLoader("UserNotificationProvider"); String message_subject = courseSite ? rb.getString("java.official") + " " + currentUserName + " " + rb.getString("java.for") + " " + termTitle : rb.getString("java.site.createdBy") + " " + currentUserName; String from = currentUser.getEmail(); String to = requestEmail; String headerTo = requestEmail; String replyTo = currentUserEmail; StringBuilder buf = new StringBuilder(); buf.append( "\n" + rb.getString("java.fromwork") + " " + serverConfigurationService.getServerName() + " " + rb.getString("java.supp") + ":\n\n"); buf.append(courseSite ? rb.getString("java.off") : rb.getString("java.site")); buf.append(" '" + title + "' (id " + id + "), " + rb.getString("java.wasset") + " "); buf.append( currentUserName + " (" + currentUserId + ", " + rb.getString("java.email2") + " " + replyTo + ") "); buf.append(rb.getString("java.on") + " " + dateDisplay); if (courseSite) { buf.append(rb.getString("java.for") + " " + termTitle + ", "); } if (notifySites != null) { int nbr_sections = notifySites.size(); if (nbr_sections > 1) { buf.append( rb.getString("java.withrost") + " " + Integer.toString(nbr_sections) + " " + rb.getString("java.sections") + "\n\n"); } else { buf.append(" " + rb.getString("java.withrost2") + "\n\n"); } for (int i = 0; i < nbr_sections; i++) { String course = (String) notifySites.get(i); buf.append(rb.getString("java.course2") + " " + course + "\n"); } } emailService.send(from, to, message_subject, buf.toString(), headerTo, replyTo, null); // send a confirmation email to site creator from = requestEmail; to = currentUserEmail; headerTo = currentUserEmail; replyTo = serverConfigurationService.getString( "setup.request", "no-reply@" + serverConfigurationService.getServerName()); String content = rb.getFormattedMessage( "java.siteCreation.confirmation", new Object[] {title, serverConfigurationService.getServerName()}); content += "\n\n" + buf.toString(); emailService.send(from, to, message_subject, content, headerTo, replyTo, null); }