/** @see org.telscenter.sail.webapp.service.offering.RunService#endRun(Run) */
 @Transactional()
 public void endRun(Run run) {
   if (run.getEndtime() == null) {
     run.setEndtime(Calendar.getInstance().getTime());
     this.runDao.save(run);
   }
 }
  /**
   * Generates the url string that users need to go to start the project
   *
   * @param httpRestTransport
   * @param request request that was made
   * @param run <code>Run</code> that the user is in
   * @param workgroup <code>Workgroup</code> that the user is in
   * @param retrieveAnnotationBundleUrl
   * @returnurl String url representation to download the jnlp and start the project
   */
  @Override
  public String generateStudentStartProjectUrlString(
      HttpRestTransport httpRestTransport,
      HttpServletRequest request,
      Run run,
      Workgroup workgroup,
      String retrieveAnnotationBundleUrl) {
    String jnlpUrl = generateLaunchProjectUrlString(httpRestTransport, run, workgroup);

    String entireUrl =
        jnlpUrl + "?" + generateRetrieveAnnotationBundleParamRequestString(request, workgroup);

    // TODO HT: put these param-generation into run/project domain object as much as possible to
    // stop
    // cluttering services
    // add jnlp.portal_baseurl and jnlp.runId to the request
    entireUrl += "&" + generatePortalBaseUrlParamRequestString(request);
    entireUrl += "&" + generateRunIdParamRequestString(run.getId());
    if (run.getProject().getFamilytag().equals(FamilyTag.UCCP)) {
      entireUrl += "&jnlp.style=UCCP";
    }

    Curnit curnit = run.getProject().getCurnit();
    String curnitOtmlUrl = "";
    try {
      curnitOtmlUrl =
          ((OtmlModuleImpl) this.moduleService.getById(curnit.getId())).getRetrieveotmlurl();
    } catch (ObjectNotFoundException e) {

    }
    entireUrl += "&sailotrunk.otmlurl=" + curnitOtmlUrl;

    return entireUrl;
  }
 /**
  * @throws ObjectNotFoundException
  * @see
  *     org.telscenter.sail.webapp.service.offering.RunService#setStudentAssetUploaderEnabled(java.lang.Long,
  *     boolean)
  */
 @Transactional
 public void setStudentAssetUploaderEnabled(Long runId, boolean isEnabled)
     throws ObjectNotFoundException {
   Run run = this.retrieveById(runId);
   run.setStudentAssetUploaderEnabled(isEnabled);
   this.runDao.save(run);
 }
  /**
   * Check if the user is in the run
   *
   * @param user the user
   * @param runId the run id
   * @return whether the user is in the run
   */
  private boolean isUserInRun(User user, Long runId) {
    boolean result = false;

    if (user != null && runId != null) {
      // get the list of runs this user is in
      List<Run> runList = runService.getRunList(user);

      Iterator<Run> runListIterator = runList.iterator();

      // loop through all the runs this user is in
      while (runListIterator.hasNext()) {
        // get a run
        Run tempRun = runListIterator.next();

        if (tempRun != null) {
          // get the run id
          Long tempRunId = tempRun.getId();

          // check if the run id matches the one we are searching for
          if (runId.equals(tempRunId)) {
            // the run id matches so the user is in the run
            result = true;
            break;
          }
        }
      }
    }

    return result;
  }
  /**
   * Check if the user is in the period
   *
   * @param user the user
   * @param runId the run id
   * @param periodId the period id
   * @return whether the user is in the period
   */
  private boolean isUserInPeriod(User user, Long runId, Long periodId) {
    boolean result = false;

    if (user != null && runId != null && periodId != null) {
      try {
        // get the run
        Run run = runService.retrieveById(runId);

        // get the period the student is in for the run
        Group periodOfStudent = run.getPeriodOfStudent(user);

        if (periodOfStudent != null) {
          // get the period id
          Long tempPeriodId = periodOfStudent.getId();

          // check if the period id matches the one we are searching for
          if (periodId.equals(tempPeriodId)) {
            // the period id matches so the user is in the period
            result = true;
          }
        }
      } catch (ObjectNotFoundException e) {
      }
    }

    return result;
  }
  /**
   * Check if a user is the owner or shared owner of a run
   *
   * @param user the signed in user
   * @param runId the run id
   * @return whether the user is an owner of the run
   */
  private boolean isUserOwnerOfRun(User user, Long runId) {
    boolean result = false;

    if (user != null && runId != null) {
      try {
        // get the run
        Run run = runService.retrieveById(runId);

        if (run != null) {
          // get the owners and shared owners
          Set<User> owners = run.getOwners();
          Set<User> sharedowners = run.getSharedowners();

          if (owners.contains(user) || sharedowners.contains(user)) {
            // the user is the owner or a shared owner
            result = true;
          }
        }
      } catch (ObjectNotFoundException e) {
        e.printStackTrace();
      }
    }

    return result;
  }
  private void handleStudentAssetManager(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ServletContext servletContext2 = this.getServletContext();
    ServletContext vlewrappercontext = servletContext2.getContext("/vlewrapper");
    User user = ControllerUtil.getSignedInUser();
    String studentuploads_base_dir = portalProperties.getProperty("studentuploads_base_dir");

    try {
      // get the run
      String runId = request.getParameter("runId");
      Run run = runService.retrieveById(new Long(runId));

      // get the project id
      Project project = run.getProject();
      Serializable projectId = project.getId();

      // set the project id into the request so the vlewrapper controller has access to it
      request.setAttribute("projectId", projectId + "");

      // get the workgroup id
      List<Workgroup> workgroupListByOfferingAndUser =
          workgroupService.getWorkgroupListByOfferingAndUser(run, user);
      Workgroup workgroup = workgroupListByOfferingAndUser.get(0);
      Long workgroupId = workgroup.getId();

      // set the workgroup id into the request so the vlewrapper controller has access to it
      request.setAttribute(
          "dirName",
          run.getId()
              + "/"
              + workgroupId
              + "/unreferenced"); // looks like /studentuploads/[runId]/[workgroupId]/unreferenced
      String commandParamter = request.getParameter("command");
      if (commandParamter != null && "studentAssetCopyForReference".equals(commandParamter)) {
        request.setAttribute(
            "referencedDirName",
            run.getId()
                + "/"
                + workgroupId
                + "/referenced"); // if we're copying student asset for reference, also pass along
                                  // the referenced dir. looks like
                                  // /studentuploads/[runId]/[workgroupId]/referenced
      }
      if (studentuploads_base_dir != null) {
        request.setAttribute("studentuploads_base_dir", studentuploads_base_dir);
      }
      // forward the request to the vlewrapper controller
      RequestDispatcher requestDispatcher =
          vlewrappercontext.getRequestDispatcher("/vle/studentassetmanager.html");
      requestDispatcher.forward(request, response);
    } catch (NumberFormatException e) {
      e.printStackTrace();
    } catch (ObjectNotFoundException e) {
      e.printStackTrace();
    }
  }
 /** @see org.telscenter.sail.webapp.service.offering.RunService#startRun(Run) */
 @Transactional()
 public void startRun(Run run) {
   if (run.getEndtime() != null) {
     run.setEndtime(null);
     Calendar reminderCal = Calendar.getInstance();
     reminderCal.add(Calendar.DATE, 30);
     run.setArchiveReminderTime(reminderCal.getTime());
     this.runDao.save(run);
   }
 }
  /**
   * @see
   *     org.telscenter.sail.webapp.service.offering.RunService#extendArchiveReminderTime(java.lang.Long)
   */
  @Transactional()
  public void extendArchiveReminderTime(Long runId) throws ObjectNotFoundException {
    Run run = this.retrieveById(runId);

    Calendar moreTime = Calendar.getInstance();
    moreTime.add(Calendar.DATE, 30);

    run.setArchiveReminderTime(moreTime.getTime());
    this.runDao.save(run);
  }
 /**
  * @see org.telscenter.sail.webapp.service.offering.RunService#updateRunName(java.lang.Long,
  *     java.lang.String)
  */
 @Transactional()
 public void updateRunName(Long runId, String name) {
   try {
     Run run = this.retrieveById(runId);
     run.setName(name);
     this.runDao.save(run);
   } catch (ObjectNotFoundException e) {
     e.printStackTrace();
   }
 }
 @Transactional()
 public void addPeriodToRun(Long runId, String name) {
   try {
     Run run = this.retrieveById(runId);
     Set<Group> periods = run.getPeriods();
     Group group = new PersistentGroup();
     group.setName(name);
     this.groupDao.save(group);
     periods.add(group);
     this.runDao.save(run);
   } catch (ObjectNotFoundException e) {
     e.printStackTrace();
   }
 }
  /**
   * @override @see
   *     org.telscenter.sail.webapp.service.offering.RunService#addSharedTeacherToRun(org.telscenter.sail.webapp.domain.impl.AddSharedTeacherParameters)
   */
  public void addSharedTeacherToRun(AddSharedTeacherParameters addSharedTeacherParameters) {
    Run run = addSharedTeacherParameters.getRun();
    String sharedOwnerUsername = addSharedTeacherParameters.getSharedOwnerUsername();
    User user = userDao.retrieveByUsername(sharedOwnerUsername);
    run.getSharedowners().add(user);
    this.runDao.save(run);

    String permission = addSharedTeacherParameters.getPermission();
    if (permission.equals(UserDetailsService.RUN_GRADE_ROLE)) {
      this.aclService.removePermission(run, BasePermission.READ, user);
      this.aclService.addPermission(run, BasePermission.WRITE, user);
    } else if (permission.equals(UserDetailsService.RUN_READ_ROLE)) {
      this.aclService.removePermission(run, BasePermission.WRITE, user);
      this.aclService.addPermission(run, BasePermission.READ, user);
    }
  }
  /**
   * Set the project meta data into the request as an attribute so that we can access it in other
   * controllers
   *
   * @param run
   * @param request
   */
  private void setProjectMetaData(Run run, HttpServletRequest request) {
    Project project = run.getProject();
    ProjectMetadata metadata = project.getMetadata();
    String projectMetaDataJSONString = metadata.toJSONString();

    request.setAttribute("projectMetaData", projectMetaDataJSONString);
  }
  /**
   * Set the project path into the request as an attribute so that we can access it in other
   * controllers
   *
   * @param run
   * @param request
   */
  private void setProjectPath(Run run, HttpServletRequest request) {
    String curriculumBaseDir = portalProperties.getProperty("curriculum_base_dir");
    String rawProjectUrl =
        (String) run.getProject().getCurnit().accept(new CurnitGetCurnitUrlVisitor());
    String projectPath = curriculumBaseDir + rawProjectUrl;

    request.setAttribute("projectPath", projectPath);
  }
  @Transactional()
  public void setInfo(Long runId, String isPaused, String showNodeId) throws Exception {
    Run run = this.retrieveById(runId);

    String runInfoString = "<isPaused>" + isPaused + "</isPaused>";
    if (showNodeId != null) {
      runInfoString += "<showNodeId>" + showNodeId + "</showNodeId>";
    }

    /*
     * when we use the info field for more info than just isPaused this
     * will need to be changed so it doesn't just completely overwrite
     * the info field
     */
    run.setInfo(runInfoString);
    this.runDao.save(run);
  }
  @Override
  protected ModelAndView handleRequestInternal(
      HttpServletRequest request, HttpServletResponse response) throws Exception {
    Workgroup workgroup =
        this.workgroupService.retrieveById(Long.parseLong(request.getParameter(WORKGROUPID)));
    Run run = this.runService.retrieveById(Long.parseLong(request.getParameter(RUNID)));
    RooloOtmlModuleImpl mod =
        (RooloOtmlModuleImpl) this.moduleService.getById(run.getProject().getCurnit().getId());
    IELO elo = this.moduleService.getEloForModule(mod);
    mod.setElo(elo);

    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject(RUN, run);
    modelAndView.addObject(WORKGROUP, workgroup);
    modelAndView.addObject(PREVIEW, request.getParameter(PREVIEW));
    modelAndView.addObject(ELO, mod.getElo());

    return modelAndView;
  }
  /**
   * @throws ObjectNotFoundException
   * @see
   *     org.telscenter.sail.webapp.service.offering.RunService#removeSharedTeacherFromRun(java.lang.String,
   *     java.lang.Long)
   */
  public void removeSharedTeacherFromRun(String username, Long runId)
      throws ObjectNotFoundException {
    Run run = this.retrieveById(runId);
    User user = userDao.retrieveByUsername(username);
    if (run == null || user == null) {
      return;
    }

    if (run.getSharedowners().contains(user)) {
      run.getSharedowners().remove(user);
      this.runDao.save(run);
      try {
        List<Permission> permissions = this.aclService.getPermissions(run, user);
        for (Permission permission : permissions) {
          this.aclService.removePermission(run, permission, user);
        }
      } catch (Exception e) {
        // do nothing. permissions might get be deleted if user requesting the deletion is not the
        // owner of the run.
      }
    }
  }
  private void handleViewStudentAssets(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ServletContext servletContext2 = this.getServletContext();
    ServletContext vlewrappercontext = servletContext2.getContext("/vlewrapper");
    User user = ControllerUtil.getSignedInUser();
    String studentuploads_base_dir = portalProperties.getProperty("studentuploads_base_dir");

    try {
      // get the run
      String runId = request.getParameter("runId");
      Run run = runService.retrieveById(new Long(runId));

      // get the project id
      Project project = run.getProject();
      Serializable projectId = project.getId();

      // set the project id into the request so the vlewrapper controller has access to it
      request.setAttribute("projectId", projectId + "");

      // set the workgroup id into the request so the vlewrapper controller has access to it
      if (studentuploads_base_dir != null) {
        request.setAttribute("studentuploads_base_dir", studentuploads_base_dir);
      }

      // workgroups is a ":" separated string of workgroups
      String workgroups = request.getParameter("workgroups");

      request.setAttribute("dirName", workgroups);

      // forward the request to the vlewrapper controller
      RequestDispatcher requestDispatcher =
          vlewrappercontext.getRequestDispatcher("/vle/studentassetmanager.html");
      requestDispatcher.forward(request, response);
    } catch (NumberFormatException e) {
      e.printStackTrace();
    } catch (ObjectNotFoundException e) {
      e.printStackTrace();
    }
  }
  /**
   * Sets the classmate, teacher and shared teacher user infos into the request object so they can
   * be retrieved by the vlewrapper servlets
   *
   * @param run
   * @param request
   */
  private void setUserInfos(Run run, HttpServletRequest request) {
    // get the signed in user info
    JSONObject myUserInfoJSONObject = RunUtil.getMyUserInfo(run, workgroupService);

    // get the classmate user infos
    JSONArray classmateUserInfosJSONArray =
        RunUtil.getClassmateUserInfos(run, workgroupService, runService);

    // get the teacher info
    JSONObject teacherUserInfoJSONObject = RunUtil.getTeacherUserInfo(run, workgroupService);

    // get the shared teacher infos
    JSONArray sharedTeacherUserInfosJSONArray =
        RunUtil.getSharedTeacherUserInfos(run, workgroupService);

    // get the run info
    JSONObject runInfoJSONObject = RunUtil.getRunInfo(run);

    // set the JSON objects to request attributes so the vlewrapper servlet can access them
    request.setAttribute("myUserInfo", myUserInfoJSONObject.toString());
    request.setAttribute("classmateUserInfos", classmateUserInfosJSONArray.toString());
    request.setAttribute("teacherUserInfo", teacherUserInfoJSONObject.toString());
    request.setAttribute("sharedTeacherUserInfos", sharedTeacherUserInfosJSONArray.toString());
    request.setAttribute("runInfo", runInfoJSONObject.toString());

    // get all the student attendance entries for this run
    List<StudentAttendance> studentAttendanceList =
        studentAttendanceService.getStudentAttendanceByRunId(run.getId());
    JSONArray studentAttendanceJSONArray = new JSONArray();

    /*
     * loop through all the student attendance entries so we can
     * create JSONObjects out of them to put in our studentAttendanceJSONArray
     */
    for (int x = 0; x < studentAttendanceList.size(); x++) {
      // get a StudenAttendance object
      StudentAttendance studentAttendance = studentAttendanceList.get(x);

      // get the JSONObject representation
      JSONObject studentAttendanceJSONObj = studentAttendance.toJSONObject();

      // add it to our array
      studentAttendanceJSONArray.put(studentAttendanceJSONObj);
    }

    /*
     * set the student attendance array as an attribute so the vlewrapper
     * context can access this data
     */
    request.setAttribute("studentAttendance", studentAttendanceJSONArray.toString());
  }
  /**
   * @see
   *     org.telscenter.sail.webapp.service.offering.RunService#updateRunStatistics(org.telscenter.sail.webapp.domain.Run)
   */
  @Transactional()
  public void updateRunStatistics(Long runId) {

    try {
      Run run = retrieveById(runId);

      /* set the current time as the last time this run was run */
      run.setLastRun(Calendar.getInstance().getTime());

      /* increment the number of times this run has been run, if
       * the run has not yet been run, the times run will be null */
      if (run.getTimesRun() == null) {
        run.setTimesRun(1);
      } else {
        run.setTimesRun(run.getTimesRun() + 1);
      }

      /* save changes */
      this.runDao.save(run);
    } catch (ObjectNotFoundException e) {
      e.printStackTrace();
    }
  }
  private void handleIdeaBasket(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ServletContext servletContext2 = this.getServletContext();
    ServletContext vlewrappercontext = servletContext2.getContext("/vlewrapper");
    User signedInUser = ControllerUtil.getSignedInUser();
    String action = request.getParameter("action");

    try {
      // get the run
      String runId = request.getParameter("runId");
      Run run = runService.retrieveById(new Long(runId));

      // get the project id
      Project project = run.getProject();
      Serializable projectId = project.getId();

      // set the project id into the request so the vlewrapper controller has access to it
      request.setAttribute("projectId", projectId + "");

      // get the authorities for the signed in user
      MutableUserDetails signedInUserDetails = signedInUser.getUserDetails();
      Collection<? extends GrantedAuthority> authorities = signedInUserDetails.getAuthorities();

      boolean isAdmin = false;
      boolean isTeacher = false;
      boolean isStudent = false;

      // this value will determine whether the user can modify anything they want in the public idea
      // basket
      boolean isPrivileged = false;

      for (GrantedAuthority authority : authorities) {
        if (authority.getAuthority().equals(UserDetailsService.ADMIN_ROLE)) {
          // user is an admin or teacher
          isAdmin = true;
          isPrivileged = true;
        } else if (authority.getAuthority().equals(UserDetailsService.TEACHER_ROLE)) {
          // user is an admin or teacher
          isTeacher = true;
          isPrivileged = true;
        }
      }

      if (!isTeacher) {
        isStudent = true;
      }

      request.setAttribute("isPrivileged", isPrivileged);

      if (isAdmin) {
        // user is an admin so we do not need to retrieve the workgroup id
      } else if (isTeacher) {
        // user is a teacher so we will retrieve their workgroup id for the run

        // get the workgroup id
        List<Workgroup> workgroupListByOfferingAndUser =
            workgroupService.getWorkgroupListByOfferingAndUser(run, signedInUser);
        // add nullpointer check
        Workgroup workgroup = workgroupListByOfferingAndUser.get(0);
        Long signedInWorkgroupId = workgroup.getId();

        // set the workgroup id into the request so the vlewrapper controller has access to it
        request.setAttribute("signedInWorkgroupId", signedInWorkgroupId + "");
      } else if (isStudent) {
        /*
         * the user is a student so we will make sure the run id
         * matches the run they are currently working on and then
         * retrieve their workgroup id for the run
         */

        HashMap<String, Run> studentsToRuns =
            (HashMap<String, Run>)
                request.getSession().getServletContext().getAttribute("studentsToRuns");

        String sessionId = request.getSession().getId();

        if (studentsToRuns != null && studentsToRuns.containsKey(sessionId)) {
          Run sessionRun = studentsToRuns.get(sessionId);
          Long sessionRunId = sessionRun.getId();

          if (sessionRunId.equals(new Long(runId))) {
            // get the workgroup id
            List<Workgroup> workgroupListByOfferingAndUser =
                workgroupService.getWorkgroupListByOfferingAndUser(run, signedInUser);
            // add nullpointer check
            Workgroup workgroup = workgroupListByOfferingAndUser.get(0);
            Long signedInWorkgroupId = workgroup.getId();

            // set the workgroup id into the request so the vlewrapper controller has access to it
            request.setAttribute("signedInWorkgroupId", signedInWorkgroupId + "");
          } else {
            // run id does not match the run that the student is logged in to
            response.sendError(
                HttpServletResponse.SC_UNAUTHORIZED,
                "Run id does not match run that student is logged in to");
            return;
          }
        } else {
          // session id was not found which means the session probably timed out
          response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Session no longer valid");
          return;
        }
      }

      // forward the request to the vlewrapper controller
      RequestDispatcher requestDispatcher =
          vlewrappercontext.getRequestDispatcher("/ideaBasket.html");
      requestDispatcher.forward(request, response);
    } catch (NumberFormatException e) {
      e.printStackTrace();
    } catch (ObjectNotFoundException e) {
      e.printStackTrace();
    }
  }
  /**
   * Creates a run based on input parameters provided.
   *
   * @param runParameters
   * @return The run created.
   * @throws CurnitNotFoundException
   */
  @Transactional(rollbackFor = {HttpStatusCodeException.class})
  public Run createRun(RunParameters runParameters) throws ObjectNotFoundException {
    Project project = runParameters.getProject();
    // Project projectCopy = projectService.copyProject(project);
    Run run = new RunImpl();
    run.setEndtime(null);
    run.setStarttime(Calendar.getInstance().getTime());
    run.setRuncode(generateUniqueRunCode());
    run.setOwners(runParameters.getOwners());
    run.setMaxWorkgroupSize(runParameters.getMaxWorkgroupSize());
    run.setProject(project);

    // use the project name for the run name
    run.setName("" + runParameters.getProject().getName());

    Calendar reminderCal = Calendar.getInstance();
    reminderCal.add(Calendar.DATE, 30);
    run.setArchiveReminderTime(reminderCal.getTime());
    if (!(run.getProject() instanceof ExternalProject)) {
      if (run.getProject().getProjectType() != ProjectType.ROLOO
          && run.getProject().getProjectType() != ProjectType.LD) {
        run.setSdsOffering(generateSdsOfferingFromParameters(runParameters));
      }
    }
    Set<String> periodNames = runParameters.getPeriodNames();
    if (periodNames != null) {
      Set<Group> periods = new TreeSet<Group>();
      for (String periodName : runParameters.getPeriodNames()) {
        Group group = new PersistentGroup();
        group.setName(periodName);
        this.groupDao.save(group);
        periods.add(group);
      }
      run.setPeriods(periods);
    }
    run.setPostLevel(runParameters.getPostLevel());

    /* if this is an LD project take snapshot of project for run and set versionId
    if(run.getProject().getProjectType()==ProjectType.LD){
    	String requester = run.getOwners().iterator().next().getUserDetails().getUsername();
    	String versionId = this.projectService.takeSnapshot(run.getProject(), requester, "For Run " + run.getName());
    	if(versionId==null || versionId.equals("failed")){
    		throw new ObjectNotFoundException("Snapshot of project failed when creating the run.", RunImpl.class);
    	} else{
    		run.setVersionId(versionId);
    	}
    }
    */

    this.runDao.save(run);
    this.aclService.addPermission(run, BasePermission.ADMINISTRATION);
    return run;
  }
 @Transactional()
 public void setExtras(Run run, String extras) throws Exception {
   run.setExtras(extras);
   this.runDao.save(run);
 }
 /**
  * @see
  *     org.telscenter.sail.webapp.service.offering.RunService#removeAnnouncementFromRun(java.lang.Long,
  *     org.telscenter.sail.webapp.domain.announcement.Announcement)
  */
 @Transactional()
 public void removeAnnouncementFromRun(Long runId, Announcement announcement) throws Exception {
   Run run = this.retrieveById(runId);
   run.getAnnouncements().remove(announcement);
   this.runDao.save(run);
 }