private String getCurrentUserId() {
   if (sessionManager == null) {
     return "test-mode-user";
   } else {
     return sessionManager.getCurrentSession().getUserId();
   }
 }
  @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();
    }
  }
  /** @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;
 }
  /**
   * 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);
  }
Ejemplo n.º 6
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);
  }
Ejemplo n.º 7
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();
    }
  }
  /** 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);
    }
  }
Ejemplo n.º 9
0
  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());
      }
    }
  }
Ejemplo n.º 10
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());
    }
  }