Example #1
0
  private Map<String, String> getPermissions(ContentEntity n) throws SDataException {
    Map<String, String> map = new HashMap<String, String>();

    if (n instanceof ContentCollection) {
      map.put("read", String.valueOf(contentHostingService.allowGetCollection(n.getId())));
      map.put("remove", String.valueOf(contentHostingService.allowRemoveCollection(n.getId())));
      map.put("write", String.valueOf(contentHostingService.allowUpdateCollection(n.getId())));

      String ref = n.getReference();

      Reference reference = entityManager.newReference(n.getReference());
      if (log.isDebugEnabled()) {
        log.debug("Got Reference " + reference + " for " + n.getReference());
      }

      Collection<?> groups = reference.getAuthzGroups();
      String user = sessionManager.getCurrentSessionUserId();
      map.put(
          "admin",
          String.valueOf(
              authZGroupService.isAllowed(
                  sessionManager.getCurrentSessionUserId(),
                  AuthzGroupService.SECURE_UPDATE_AUTHZ_GROUP,
                  groups)));
    } else {
      map.put("read", String.valueOf(contentHostingService.allowGetResource(n.getId())));
      map.put("remove", String.valueOf(contentHostingService.allowRemoveResource(n.getId())));
      map.put("write", String.valueOf(contentHostingService.allowUpdateResource(n.getId())));
    }
    return map;
  }
  /** @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);
  }
 /**
  * Return current user locale.
  *
  * @return user's Locale object
  */
 private Locale getCurrentUserLocale() {
   Locale loc = null;
   try {
     // check if locale is requested for specific user
     String userId = M_sm.getCurrentSessionUserId();
     if (userId != null) {
       Preferences prefs = M_ps.getPreferences(userId);
       ResourceProperties locProps = prefs.getProperties(ResourceLoader.APPLICATION_ID);
       String localeString = locProps.getProperty(ResourceLoader.LOCALE_KEY);
       // Parse user locale preference if set
       if (localeString != null) {
         String[] locValues = localeString.split("_");
         if (locValues.length > 1)
           // language, country
           loc = new Locale(locValues[0], locValues[1]);
         else if (locValues.length == 1)
           // language
           loc = new Locale(locValues[0]);
       }
       if (loc == null) loc = Locale.getDefault();
     } else {
       loc =
           (Locale)
               M_sm.getCurrentSession()
                   .getAttribute(ResourceLoader.LOCALE_KEY + M_sm.getCurrentSessionUserId());
     }
   } catch (NullPointerException e) {
     loc = Locale.getDefault();
   }
   return loc;
 }
Example #4
0
  /**
   * Get the Session related to the given sessionid
   *
   * @param sessionid the id of the session to retrieve
   * @return the session, if it is active @ if session is inactive
   */
  protected Session establishSession(String sessionid) {
    Session s = sessionManager.getSession(sessionid);

    if (s == null) {
      throw new RuntimeException("Session \"" + sessionid + "\" is not active");
    }
    s.setActive();
    sessionManager.setCurrentSession(s);
    return s;
  }
 private String getCurrentUserId() {
   if (sessionManager == null) {
     return "test-mode-user";
   } else {
     return sessionManager.getCurrentSession().getUserId();
   }
 }
Example #6
0
  /**
   * Parse and load selected XML data file
   *
   * @return String that is used to determine the place where control is to be sent in
   *     ControlImportProducer (reportNavigationCases method)
   * @throws SecurityException
   */
  public String process() throws SecurityException {
    ToolSession toolSession = sessionManager.getCurrentToolSession();
    List refs = null;
    String id = null;
    if (toolSession.getAttribute(FilePickerHelper.FILE_PICKER_CANCEL) == null
        && toolSession.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null) {
      refs = (List) toolSession.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
      if (refs == null || refs.size() != 1) {
        return "no-reference";
      }
      Reference ref = (Reference) refs.get(0);
      id = ref.getId();
    }
    try {
      contentHostingService.checkResource(id);
    } catch (PermissionException e) {
      return "permission-exception";
    } catch (IdUnusedException e) {
      return "idunused-exception";
    } catch (TypeException e) {
      return "type-exception";
    }
    try {
      evalImportLogic.load(id);
    } catch (Exception e) {
      return "exception";
    }

    toolSession.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
    toolSession.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL);
    return "importing";
  }
 public TaggableItem getItem(
     String itemRef, TaggingProvider provider, boolean getMyItemOnly, String taggedItem) {
   TaggableItem item = null;
   if (checkReference(itemRef)) {
     // Only return item to a specified rating (evalutation) provider
     if (ratingProviderIds.contains(provider.getId())) {
       WizardReference reference = WizardReference.getReference(itemRef);
       if (reference != null) {
         WizardPage page = matrixManager.getWizardPage(idManager.getId(reference.getId()));
         if (page != null
             && (page.getStatus().equals(MatrixFunctionConstants.PENDING_STATUS)
                 || page.getStatus().equals(MatrixFunctionConstants.COMPLETE_STATUS))
             && (page.getOwner()
                     .getId()
                     .getValue()
                     .equals(sessionManager.getCurrentSessionUserId())
                 || (!getMyItemOnly && canEvaluate(page)))) {
           item = getItem(page);
         }
       }
     } else {
       // Notify other tagging providers that they aren't accepted here
       // yet
       logger.warn(this + ".getItem(): Provider with id " + provider.getId() + " not allowed!");
     }
   }
   return item;
 }
Example #8
0
  private static void setPreferenceList(String name, Collection values) throws Exception {
    PreferencesEdit prefsEdit = null;
    String userId = M_sm.getCurrentSessionUserId();
    try {
      prefsEdit = M_ps.edit(userId);
    } catch (IdUnusedException e) {
      prefsEdit = M_ps.add(userId);
    }
    try {
      ResourcePropertiesEdit props = prefsEdit.getPropertiesEdit(PREFS_KEY);

      if (values == null) {
        props.removeProperty(name);
      } else {
        List existing = props.getPropertyList(name);
        Iterator it = values.iterator();
        while (it.hasNext()) {
          String value = (String) it.next();
          if (existing == null || !existing.contains(value))
            props.addPropertyToList(name, value.toString());
        }
      }
    } catch (Exception e) {
      if (prefsEdit != null) M_ps.cancel(prefsEdit);
      M_ps.cancel(prefsEdit);
      throw e;
    }
    M_ps.commit(prefsEdit);
  }
Example #9
0
  /**
   * @throws SDataException
   * @throws RepositoryException
   */
  public CHSNodeMap(ContentEntity n, int depth, ResourceDefinition rp) throws SDataException {
    String lock = ContentHostingService.AUTH_RESOURCE_HIDDEN;
    sessionManager = Kernel.sessionManager();
    entityManager = Kernel.entityManager();
    String userId = sessionManager.getCurrentSessionUserId();
    String reference = n.getReference();
    Reference referenceObj = entityManager.newReference(reference);
    Collection<?> groups = referenceObj.getAuthzGroups();

    boolean canSeeHidden = Kernel.securityService().unlock(userId, lock, reference, groups);

    if (!canSeeHidden && !n.isAvailable()) {
      throw new SDataAccessException(403, "Permission denied on item");
    }
    contentHostingService = Kernel.contentHostingService();
    authZGroupService = Kernel.authzGroupService();
    depth--;
    put("mixinNodeType", getMixinTypes(n));
    put("properties", getProperties(n));
    put("name", getName(n));
    if (rp != null) {
      put("path", rp.getExternalPath(n.getId()));
    }
    put("permissions", getPermissions(n));

    if (n instanceof ContentResource) {
      put("primaryNodeType", "nt:file");
      addFile((ContentResource) n);
    } else {
      put("primaryNodeType", "nt:folder");
      addFolder((ContentCollection) n, rp, depth);
    }
  }
  @SuppressWarnings("unchecked")
  private void loadNewUserMail() {
    try {
      // we need a user session to avoind potential NPE's
      Session sakaiSession = sessionManager.getCurrentSession();
      sakaiSession.setUserId(ADMIN);
      sakaiSession.setUserEid(ADMIN);
      InputStream in =
          ETSUserNotificationProviderImpl.class
              .getClassLoader()
              .getResourceAsStream("notifyNewuser.xml");
      Document document = new SAXBuilder().build(in);
      List<Element> it = document.getRootElement().getChildren("emailTemplate");

      for (int i = 0; i < it.size(); i++) {
        Element xmlTemplate = (Element) it.get(i);
        xmlToTemplate(xmlTemplate, NOTIFY_NEW_USER);
      }
      sakaiSession.setUserId(null);
      sakaiSession.setUserEid(null);

    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (JDOMException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /**
   * Convenience method to switch authn/authz identities. TODO Move this frequently-needed helper
   * logic into the base class.
   *
   * @param userEid
   */
  public void actAsUserEid(String userEid) {
    if (log.isDebugEnabled()) log.debug("actAsUserEid=" + userEid);

    SessionManager sessionManager = getService(SessionManager.class);

    String userId;
    try {
      userId = userDirectoryService.getUserId(userEid);
    } catch (UserNotDefinedException e) {
      log.error("Could not act as user EID=" + userEid, e);
      return;
    }
    Session session = sessionManager.getCurrentSession();
    session.setUserEid(userEid);
    session.setUserId(userId);
    authzGroupService.refreshUser(userId);
  }
Example #12
0
  private static void clearPreferenceList(String name) throws Exception {
    PreferencesEdit prefsEdit = null;
    try {
      prefsEdit = M_ps.edit(M_sm.getCurrentSessionUserId());
      ResourcePropertiesEdit props = prefsEdit.getPropertiesEdit(PREFS_KEY);

      props.removeProperty(name);
    } catch (Exception e) {
      M_ps.cancel(prefsEdit);
      throw e;
    }
    M_ps.commit(prefsEdit);
  }
Example #13
0
  private static void setPreferenceString(String name, String value) throws Exception {
    PreferencesEdit prefsEdit = null;
    String userId = M_sm.getCurrentSessionUserId();
    try {
      prefsEdit = M_ps.edit(userId);
    } catch (IdUnusedException e) {
      prefsEdit = M_ps.add(userId);
    }
    try {
      ResourcePropertiesEdit props = prefsEdit.getPropertiesEdit(PREFS_KEY);

      if (value == null) {
        props.removeProperty(name);
      } else {
        props.addProperty(name, value.toString());
      }
    } catch (Exception e) {
      if (prefsEdit != null) M_ps.cancel(prefsEdit);
      throw e;
    }
    M_ps.commit(prefsEdit);
  }
 public boolean allowRemoveTags(TaggableActivity activity) {
   WizardPageDefinition pageDef = (WizardPageDefinition) activity.getObject();
   // Try to get a wizard page sequence
   WizardPageSequence ps = wizardManager.getWizardPageSeqByDef(pageDef.getId());
   boolean authorized = false;
   if (ps != null) {
     Wizard wizard = ps.getCategory().getWizard();
     /*
      * If you own the wizard, or if you can delete wizards, or if you
      * can revise wizards, then you are able to delete page definitions
      * and can, therefore, remove tags.
      */
     authorized =
         sessionManager
                 .getCurrentSessionUserId()
                 .equalsIgnoreCase(wizard.getOwner().getId().getValue())
             || authzManager.isAuthorized(WizardFunctionConstants.EDIT_WIZARD, wizard.getId())
             || authzManager.isAuthorized(WizardFunctionConstants.DELETE_WIZARD, wizard.getId());
   } else {
     ScaffoldingCell cell = matrixManager.getScaffoldingCellByWizardPageDef(pageDef.getId());
     /*
      * If you can create or delete scaffolding, then you are able to
      * delete scaffolding cells and can, therefore, remove tags.
      */
     authorized =
         authzManager.isAuthorized(
                 MatrixFunctionConstants.CREATE_SCAFFOLDING, cell.getScaffolding().getId())
             || authzManager.isAuthorized(
                 MatrixFunctionConstants.DELETE_SCAFFOLDING_ANY, cell.getScaffolding().getId())
             || (authzManager.isAuthorized(
                     MatrixFunctionConstants.DELETE_SCAFFOLDING_OWN, cell.getScaffolding().getId())
                 && cell.getScaffolding()
                     .getOwner()
                     .getId()
                     .equals(getAuthnManager().getAgent().getId()));
   }
   return authorized;
 }
  /** {@inheritDoc} */
  public String getUserHomeUrl() {
    // get the configured URL (the text "#UID#" will be repalced with the current logged in user id
    // NOTE: this is relative to the server root
    String rv = (String) properties.get("userHomeUrl");

    // form a site based portal id if not configured
    if (rv == null) {
      rv = (String) properties.get("portalPath") + "/site/~#UID#";
    }

    // check for a logged in user
    String user = sessionManager.getCurrentSessionUserId();
    boolean loggedIn = (user != null);

    // if logged in, replace the UID in the pattern
    if (loggedIn) {
      rv = rv.replaceAll("#UID#", user);
    }

    // make it full, adding the server root
    rv = getServerUrl() + rv;

    return rv;
  }
  public void fillComponents(
      UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
    String locationId = externalLogic.getCurrentLocationId();
    ToolSession session = sessionManager.getCurrentToolSession();

    session.setAttribute(PermissionsHelper.TARGET_REF, locationId);
    session.setAttribute(
        PermissionsHelper.DESCRIPTION,
        messageLocator.getMessage(
            "mailsender.permissions.header", externalLogic.getCurrentSiteTitle()));
    session.setAttribute(PermissionsHelper.PREFIX, "mailtool.");

    List<String> perms = externalLogic.getPermissionKeys();
    HashMap<String, String> pRbValues = new HashMap<String, String>();
    for (int i = 0; i < perms.size(); i++) {
      String perm = perms.get(i);
      String descr = messageLocator.getMessage("desc-" + perm);
      pRbValues.put("desc-" + perm, descr);
    }

    session.setAttribute("permissionDescriptions", pRbValues);
    UIOutput.make(tofill, HelperViewParameters.HELPER_ID, HELPER);
    UICommand.make(tofill, HelperViewParameters.POST_HELPER_BINDING, "", null);
  }
Example #17
0
  /**
   * doImport called when "eventSubmit_doBatch_Archive" is in the request parameters to archive a
   * bunch of sites that match the criteria NOTE. This performs exactly as per a normal archive. Ie
   * if you archive a site twice, you get two copies of the resources. A change needs to be made to
   * the archive service to clean out the archives before each run.
   */
  public void doBatch_Archive(RunData data, Context context) {

    SessionState state =
        ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());

    if (!securityService.isSuperUser()) {
      addAlert(state, rb.getString("archive.batch.auth"));
      return;
    }

    final String selectedTerm = (String) state.getAttribute("selectedTerm");
    final List<SparseSite> sites = (List<SparseSite>) state.getAttribute("sites");
    final Session currentSession =
        sessionManager.getCurrentSession(); // need to pass this into the new thread
    final User currentUser =
        userDirectoryService.getCurrentUser(); // need to pass this into the new thread

    // do the archive in a new thread
    Runnable backgroundRunner =
        new Runnable() {
          public void run() {
            try {
              archiveSites(sites, selectedTerm, currentSession, currentUser);
            } catch (IllegalStateException e) {
              throw e;
            } catch (Exception e) {
              log.error("Batch Archive background runner thread died: " + e, e);
            }
          }
        };
    Thread backgroundThread = new Thread(backgroundRunner);
    backgroundThread.setDaemon(true);
    backgroundThread.start();

    state.setAttribute(STATE_MODE, BATCH_MODE);
  }
  public void fillComponents(
      UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
    ViewSubmissionsViewParams params = (ViewSubmissionsViewParams) viewparams;
    // make sure that we have an AssignmentID to work with
    if (params.assignmentId == null) {
      // ERROR SHOULD BE SET, OTHERWISE TAKE BACK TO ASSIGNMENT_LIST
      messages.addMessage(new TargettedMessage("GeneralActionError"));
      return;
    }
    assignmentId = params.assignmentId;
    Assignment2 assignment = assignmentLogic.getAssignmentByIdWithAssociatedData(assignmentId);

    String currUserId = externalLogic.getCurrentUserId();

    boolean contentReviewEnabled =
        assignment.isContentReviewEnabled()
            && contentReviewLogic.isContentReviewAvailable(assignment.getContextId());

    // let's double check that none of the associated groups were deleted from the site
    boolean displayGroupDeletionWarning = false;
    if (assignment.getAssignmentGroupSet() != null
        && !assignment.getAssignmentGroupSet().isEmpty()) {
      Collection<Group> siteGroups = externalLogic.getSiteGroups(assignment.getContextId());
      List<String> groupIds = new ArrayList<String>();
      if (siteGroups != null) {
        for (Group group : siteGroups) {
          groupIds.add(group.getId());
        }
      }

      for (AssignmentGroup assignGroup : assignment.getAssignmentGroupSet()) {
        if (!groupIds.contains(assignGroup.getGroupId())) {
          displayGroupDeletionWarning = true;
          break;
        }
      }
    }

    if (displayGroupDeletionWarning) {
      UIOutput.make(
          tofill,
          "deleted_group",
          messageLocator.getMessage("assignment2.assignment_grade-assignment.group_deleted"));
    }

    // Edit Permission
    boolean userMayEditAssign =
        permissionLogic.isUserAllowedToEditAssignment(currUserId, assignment);
    boolean userMayManageSubmissions =
        permissionLogic.isUserAllowedToManageSubmissionsForAssignment(currUserId, assignment);

    // get parameters
    if (params.sort_by == null) params.sort_by = DEFAULT_SORT_BY;
    if (params.sort_dir == null) params.sort_dir = DEFAULT_SORT_DIR;

    UIVerbatim.make(
        tofill, "defaultSortBy", HTMLUtil.emitJavascriptVar("defaultSortBy", DEFAULT_SORT_BY));

    // we need to retrieve the history for the release/retract feedback logic
    List<AssignmentSubmission> submissions =
        submissionLogic.getViewableSubmissionsWithHistoryForAssignmentId(
            assignmentId, params.groupId);
    List<String> studentIdList = new ArrayList<String>();
    if (submissions != null) {
      for (AssignmentSubmission submission : submissions) {
        studentIdList.add(submission.getUserId());
      }
    }

    // The following is some code to populate the sort order/page size, if
    // it's already been put in session state by the entity provider.
    Long pagesize = null;
    String orderBy = null;
    Boolean ascending = null;
    ToolSession toolSession = sessionManager.getCurrentToolSession();
    if (toolSession.getAttribute(Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR)
        != null) {
      Map attr =
          (Map)
              toolSession.getAttribute(
                  Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR);
      if (attr.containsKey(
          Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_PAGE_SIZE)) {
        pagesize =
            (Long)
                attr.get(Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_PAGE_SIZE);
      }
      if (attr.containsKey(
          Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_ORDER_BY)) {
        orderBy =
            (String)
                attr.get(Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_ORDER_BY);
      }
      if (attr.containsKey(
          Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_ASCENDING)) {
        ascending =
            (Boolean)
                attr.get(Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_ASCENDING);
      }
    }

    // if assign is graded, retrieve the gb details, if appropriate
    GradebookItem gbItem = null;
    boolean gbItemExists = false;
    boolean gradesReleased = false;
    // user may view the associated gradebook item
    boolean userMayViewGbItem = false;
    // user has grading privileges for this gb item
    boolean userMayGrade = false;
    boolean userMayReleaseGrades = false;

    if (assignment.isGraded() && assignment.getGradebookItemId() != null) {
      userMayViewGbItem =
          gradebookLogic.isCurrentUserAbleToViewGradebookItem(
              assignment.getContextId(), assignment.getGradebookItemId());

      if (userMayViewGbItem) {
        // user may grade if there is at least one gradable student among the submissions
        List<String> gradableStudents =
            gradebookLogic.getFilteredStudentsForGradebookItem(
                currUserId,
                assignment.getContextId(),
                assignment.getGradebookItemId(),
                AssignmentConstants.GRADE,
                studentIdList);
        userMayGrade = gradableStudents != null && !gradableStudents.isEmpty();
        userMayReleaseGrades = gradebookLogic.isCurrentUserAbleToEdit(assignment.getContextId());

        try {
          gbItem =
              gradebookLogic.getGradebookItemById(
                  assignment.getContextId(), assignment.getGradebookItemId());
          gbItemExists = true;
          gradesReleased = gbItem.isReleased();
        } catch (GradebookItemNotFoundException ginfe) {
          if (log.isDebugEnabled())
            log.debug("Gb item with id: " + assignment.getGradebookItemId() + " no longer exists!");
          gbItem = null;
        }
      }
    }

    // if user has grading privileges but item no longer exists, display warning
    // to user
    if (assignment.isGraded() && userMayViewGbItem && !gbItemExists) {
      UIOutput.make(
          tofill,
          "no_gb_item",
          messageLocator.getMessage("assignment2.assignment_grade-assignment.gb_item_deleted"));
    }

    // We need to check if it's a non electronic submission.  If it is, we don't want to have
    // the submitted columns appear (Submitted and Submission Status).
    // We pass in the boolean parameter nonElectronicSubmission to viewSubmission.js (specifically
    // snn2subview.init()),
    // where logic is there to use this parameter.
    boolean nonElectronicSubmission = false;

    if (assignment.getSubmissionType() == AssignmentConstants.SUBMIT_NON_ELECTRONIC) {
      nonElectronicSubmission = true;
    }

    UIInitBlock.make(
        tofill,
        "asnn2subview-init",
        "asnn2subview.init",
        new Object[] {
          assignmentId,
          externalLogic.getCurrentContextId(),
          placement.getId(),
          submissions.size(),
          assignment.isGraded(),
          contentReviewEnabled,
          nonElectronicSubmission,
          pagesize,
          orderBy,
          ascending,
          gradesReleased,
          params.pageIndex
        });

    // Breadcrumbs
    UIInternalLink.make(
        tofill,
        "breadcrumb",
        messageLocator.getMessage("assignment2.assignment_list-sortview.heading"),
        new SimpleViewParameters(ListProducer.VIEW_ID));
    UIMessage.make(
        tofill,
        "last_breadcrumb",
        "assignment2.assignment_grade-assignment.heading",
        new Object[] {assignment.getTitle()});

    // ACTION BAR
    boolean displayReleaseGrades = false;
    boolean displayReleaseFB = false;
    boolean displayDownloadAll = false;
    boolean displayUploadAll = false;

    if (userMayEditAssign || userMayManageSubmissions) {
      UIOutput.make(tofill, "navIntraTool");
    }

    // RELEASE GRADES
    // don't display this option if the gb item doesn't exist anymore
    if (userMayReleaseGrades && assignment.isGraded() && gbItemExists) {
      displayReleaseGrades = true;

      // determine if grades have been released yet
      String releaseLinkText =
          messageLocator.getMessage("assignment2.assignment_grade-assignment.grades.release");
      if (gradesReleased) {
        releaseLinkText =
            messageLocator.getMessage("assignment2.assignment_grade-assignment.grades.retract");
      }

      UIForm releaseGradesForm = UIForm.make(tofill, "release_grades_form");
      UICommand releaseGradesButton = UICommand.make(releaseGradesForm, "release_grades");

      UIOutput.make(tofill, "release_grades_li");
      UIInternalLink releaseGradesLink =
          UIInternalLink.make(tofill, "release_grades_link", releaseLinkText, viewparams);
      Map<String, String> idmap = new HashMap<String, String>();
      idmap.put(
          "onclick",
          "asnn2.releaseGradesDialog('"
              + releaseGradesButton.getFullID()
              + "', '"
              + assignment.getContextId()
              + "', '"
              + assignment.getGradebookItemId()
              + "', '"
              + !gradesReleased
              + "'); return false;");
      releaseGradesLink.decorate(new UIFreeAttributeDecorator(idmap));

      makeReleaseGradesDialog(gradesReleased, assignment, tofill);
    }

    // RELEASE FEEDBACK
    if (userMayManageSubmissions) {
      displayReleaseFB = true;
      makeReleaseFeedbackLink(tofill, params, submissions);
    }

    // DOWNLOAD ALL
    if (userMayManageSubmissions) {
      displayDownloadAll = true;

      ZipViewParams zvp = new ZipViewParams("zipSubmissions", assignmentId);
      UIInternalLink.make(
          tofill,
          "downloadall",
          UIMessage.make("assignment2.assignment_grade-assignment.downloadall.button"),
          zvp);
    }

    // UPLOAD GRADES & FEEDBACK
    if (userMayManageSubmissions) {
      displayUploadAll = true;

      AssignmentViewParams avp = new AssignmentViewParams("uploadall", assignmentId);
      if (assignment.isGraded() && gbItemExists && userMayGrade) {
        UIInternalLink.make(
            tofill,
            "uploadall",
            UIMessage.make("assignment2.uploadall.breadcrumb.upload.graded"),
            avp);
      } else {
        UIInternalLink.make(
            tofill,
            "uploadall",
            UIMessage.make("assignment2.uploadall.breadcrumb.upload.ungraded"),
            avp);
      }
    }

    // handle those pesky separators
    if (displayReleaseGrades && (displayReleaseFB || displayUploadAll || displayDownloadAll)) {
      UIOutput.make(tofill, "release_grades_sep");
    }

    if (displayReleaseFB && (displayUploadAll || displayDownloadAll)) {
      UIOutput.make(tofill, "release_feedback_sep");
    }

    if (displayDownloadAll && displayUploadAll) {
      UIOutput.make(tofill, "downloadall_sep");
    }

    UIMessage.make(tofill, "page-title", "assignment2.assignment_grade-assignment.title");

    // now make the "View By Sections/Groups" filter
    makeViewByGroupFilter(tofill, params, assignment);

    /*
     * Form for assigning a grade to all submissions without a grade.
     * Do not allow grading if gbItem is null - it must have been deleted
     */
    if (submissions != null
        && !submissions.isEmpty()
        && userMayGrade
        && assignment.isGraded()
        && gbItemExists) {
      createApplyToUngradedWidget(assignment, tofill, params, "unassigned-apply-form0:");
      createApplyToUngradedWidget(assignment, tofill, params, "unassigned-apply-form1:");
    }

    // Confirmation Dialogs
    // These are only added here for internationalization. They are not part
    // of a real form.
    UICommand.make(
        tofill,
        "release-feedback-confirm",
        UIMessage.make("assignment2.dialogs.release_all_feedback.confirm"));
    UICommand.make(
        tofill,
        "release-feedback-cancel",
        UIMessage.make("assignment2.dialogs.release_all_feedback.cancel"));

    UICommand.make(
        tofill,
        "retract-feedback-confirm",
        UIMessage.make("assignment2.dialogs.retract_all_feedback.confirm"));
    UICommand.make(
        tofill,
        "retract-feedback-cancel",
        UIMessage.make("assignment2.dialogs.retract_all_feedback.cancel"));
  }
Example #19
0
 /**
  * Get the current user preference value. First attempt Preferences, then defaults from
  * sakai.properties.
  *
  * @param name The property name.
  * @return The preference value or null if not set.
  */
 private static String getPreferenceString(String name) {
   Preferences prefs = M_ps.getPreferences(M_sm.getCurrentSessionUserId());
   ResourceProperties rp = prefs.getProperties(PREFS_KEY);
   String value = rp.getProperty(name);
   return value;
 }
Example #20
0
 /**
  * Get the current user preference list value. First attempt Preferences, then defaults from
  * sakai.properties.
  *
  * @param name The property name.
  * @return The preference list value or null if not set.
  */
 private static List getPreferenceList(String name) {
   Preferences prefs = M_ps.getPreferences(M_sm.getCurrentSessionUserId());
   ResourceProperties rp = prefs.getProperties(PREFS_KEY);
   List l = rp.getPropertyList(name);
   return l;
 }
Example #21
0
  /**
   * 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();
    }
  }
  public void processEmailTemplates(List<String> templatePaths) {

    final String ADMIN = "admin";

    Persister persister = new Persister();
    for (String templatePath : templatePaths) {

      log.debug("Processing template: " + templatePath);

      InputStream in = getClass().getClassLoader().getResourceAsStream(templatePath);

      if (in == null) {
        log.warn("Could not load resource from '" + templatePath + "'. Skipping ...");
        continue;
      }

      EmailTemplate template = null;
      try {
        template = persister.read(EmailTemplate.class, in);
      } catch (Exception e) {
        log.warn(
            "Error processing template: '"
                + templatePath
                + "', "
                + e.getClass()
                + ":"
                + e.getMessage()
                + ". Skipping ...");
        continue;
      }

      // check if we have an existing template of this key and locale
      // its possible the template has no locale set
      // The locale could also be the Default
      Locale loc = null;
      if (template.getLocale() != null
          && !"".equals(template.getLocale())
          && !EmailTemplate.DEFAULT_LOCALE.equals(template.getLocale())) {
        loc = LocaleUtils.toLocale(template.getLocale());
      }

      EmailTemplate existingTemplate = getEmailTemplateNoDefault(template.getKey(), loc);
      if (existingTemplate == null) {
        // no existing, save this one
        Session sakaiSession = sessionManager.getCurrentSession();
        sakaiSession.setUserId(ADMIN);
        sakaiSession.setUserEid(ADMIN);
        saveTemplate(template);
        sakaiSession.setUserId(null);
        sakaiSession.setUserId(null);
        log.info(
            "Saved email template: " + template.getKey() + " with locale: " + template.getLocale());
        continue; // skip to next
      }

      // check version, if local one newer than persisted, update it - SAK-17679
      // also update the locale - SAK-20987
      int existingTemplateVersion =
          existingTemplate.getVersion() != null ? existingTemplate.getVersion().intValue() : 0;
      if (template.getVersion() > existingTemplateVersion) {
        existingTemplate.setSubject(template.getSubject());
        existingTemplate.setMessage(template.getMessage());
        existingTemplate.setHtmlMessage(template.getHtmlMessage());
        existingTemplate.setVersion(template.getVersion());
        existingTemplate.setOwner(template.getOwner());
        existingTemplate.setLocale(template.getLocale());

        Session sakaiSession = sessionManager.getCurrentSession();
        sakaiSession.setUserId(ADMIN);
        sakaiSession.setUserEid(ADMIN);
        updateTemplate(existingTemplate);
        sakaiSession.setUserId(null);
        sakaiSession.setUserId(null);
        log.info(
            "Updated email template: "
                + template.getKey()
                + " with locale: "
                + template.getLocale());
      }
    }
  }
 private String getCurrentUser() {
   if (TestUtil.isRunningTests()) {
     return "test-user";
   }
   return sessionManager.getCurrentSessionUserId();
 }
  /** 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);
    }
  }
Example #25
0
  /**
   * Respond to access requests.
   *
   * @param req The servlet request.
   * @param res The servlet response.
   * @throws ServletException.
   * @throws IOException.
   */
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    // support two "/" separated parameters [1] and [2]) - both get presence updated, the first is
    // the address for delivery (second optional)
    String[] parts = req.getPathInfo().split("/");

    if ((parts.length == 2) || (parts.length == 3)) {
      String placementId = parts[1];

      // if we are in a newly created session where we had an invalid (presumed timed out) session
      // in the request,
      // send script to cause a sakai top level redirect
      if (ThreadLocalManager.get(SessionManager.CURRENT_INVALID_SESSION) != null) {
        String loggedOutUrl = ServerConfigurationService.getLoggedOutUrl();
        if (M_log.isDebugEnabled())
          M_log.debug("sending top redirect: " + placementId + " : " + loggedOutUrl);
        sendTopRedirect(res, loggedOutUrl);
      } else {
        String requestUserId = req.getParameter("userId");
        Session session = sessionManager.getCurrentSession();

        if (requestUserId == null || requestUserId.equals(session.getUserId())) {
          // compute our courier delivery address: this placement in this session
          String deliveryId = session.getId() + placementId;

          // find all deliveries for the requested deivery address
          List deliveries = CourierService.getDeliveries(deliveryId);

          // see if any DeliveryProviders have deliveries
          List<DeliveryProvider> providers = CourierService.getDeliveryProviders();
          if (providers != null) {
            List<Delivery> moreDeliveries = new ArrayList<Delivery>();
            for (DeliveryProvider provider : providers) {
              List<Delivery> d = provider.getDeliveries(session.getId(), placementId);
              if (d != null && !d.isEmpty()) {
                moreDeliveries.addAll(d);
              }
            }
            if (moreDeliveries.isEmpty()) {
              // use deliveries
            } else if (deliveries.isEmpty()) {
              deliveries = moreDeliveries;
            } else {
              // both lists have deliveries, so add moreDeliveries to deliveries
              deliveries.addAll(moreDeliveries);
            }
          }

          // form the reply
          sendDeliveries(res, deliveries);

          // refresh our presence at the location (placement)
          if (M_log.isDebugEnabled()) M_log.debug("setting presence: " + placementId);
          PresenceUpdater.setPresence(placementId);

          // register another presence if present
          if (parts.length == 3) {
            String secondPlacementId = parts[2];
            if (M_log.isDebugEnabled())
              M_log.debug("setting second presence: " + secondPlacementId);
            PresenceUpdater.setPresence(secondPlacementId);
          }
        } else {
          // This courier request was not meant for this user (i.e., session), so we won't honour it
          M_log.debug(
              "out-of-session courier request: requestUserId="
                  + requestUserId
                  + " session user="******"bad courier request: " + req.getPathInfo());
      sendDeliveries(res, new Vector());
    }
  }