private UUID[] personCollectionToUuidAray(Collection<Person> personCollection) {
   UUID[] uuidArray = new UUID[personCollection.size()];
   int i = 0;
   for (Person person : personCollection) {
     uuidArray[i] = person.getId();
     i++;
   }
   return uuidArray;
 }
 private void ensureValidAlertedOnPersonStateNoFail(Person person) {
   try {
     ensureValidAlertedOnPersonStateOrFail(person);
   } catch (Exception e) {
     LOGGER.error(
         "Unable to set a program status or student type on "
             + "person '{}'. This is likely to prevent that person "
             + "record from appearing in caseloads, student searches, "
             + "and some reports.",
         person.getId(),
         e);
   }
 }
  @Override
  public EarlyAlert create(@NotNull final EarlyAlert earlyAlert)
      throws ObjectNotFoundException, ValidationException {
    // Validate objects
    if (earlyAlert == null) {
      throw new IllegalArgumentException("EarlyAlert must be provided.");
    }

    if (earlyAlert.getPerson() == null) {
      throw new ValidationException("EarlyAlert Student data must be provided.");
    }

    final Person student = earlyAlert.getPerson();

    // Figure student advisor or early alert coordinator
    final UUID assignedAdvisor = getEarlyAlertAdvisor(earlyAlert);
    if (assignedAdvisor == null) {
      throw new ValidationException(
          "Could not determine the Early Alert Advisor for student ID " + student.getId());
    }

    if (student.getCoach() == null || assignedAdvisor.equals(student.getCoach().getId())) {
      student.setCoach(personService.get(assignedAdvisor));
    }

    ensureValidAlertedOnPersonStateNoFail(student);

    // Create alert
    final EarlyAlert saved = getDao().save(earlyAlert);

    // Send e-mail to assigned advisor (coach)
    try {
      sendMessageToAdvisor(saved, earlyAlert.getEmailCC());
    } catch (final SendFailedException e) {
      LOGGER.warn("Could not send Early Alert message to advisor.", e);
      throw new ValidationException(
          "Early Alert notification e-mail could not be sent to advisor. Early Alert was NOT created.",
          e);
    }

    // Send e-mail CONFIRMATION to faculty
    try {
      sendConfirmationMessageToFaculty(saved);
    } catch (final SendFailedException e) {
      LOGGER.warn("Could not send Early Alert confirmation to faculty.", e);
      throw new ValidationException(
          "Early Alert confirmation e-mail could not be sent. Early Alert was NOT created.", e);
    }

    return saved;
  }
  /**
   * Persist any changes to the plan instance.
   *
   * @param id Explicit id to the instance to persist.
   * @param obj Full instance to persist.
   * @return The update data object instance.
   * @throws ObjectNotFoundException If specified object could not be found.
   * @throws ValidationException If the specified id is null.
   * @throws CloneNotSupportedException
   */
  @PreAuthorize("hasRole('ROLE_PERSON_MAP_WRITE')")
  @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
  public @ResponseBody PlanTO save(
      @PathVariable final UUID id, @Valid @RequestBody final PlanTO obj)
      throws ValidationException, ObjectNotFoundException, CloneNotSupportedException {
    if (id == null) {
      throw new ValidationException(
          "You submitted without an id to the save method.  Did you mean to create?");
    }

    if (obj.getId() == null) {
      obj.setId(id);
    }
    final Plan oldPlan = getService().get(id);
    final Person oldOwner = oldPlan.getOwner();

    SspUser currentUser = getSecurityService().currentlyAuthenticatedUser();

    // If the currently logged in user is not the owner of this plan
    // we need to create a clone then save it.
    if (currentUser.getPerson().getId().equals(oldOwner.getId())) {
      final Plan model = getFactory().from(obj);
      Plan savedPlan = getService().save(model);
      if (null != model) {
        return validatePlan(new PlanTO(savedPlan));
      }
    } else {
      obj.setId(null);
      Plan model = getFactory().from(obj);
      final Plan clonedPlan = getService().copyAndSave(model);
      if (null != clonedPlan) {
        return validatePlan(new PlanTO(clonedPlan));
      }
    }

    return null;
  }
  @RenderMapping(params = "action=enterAlert")
  public ModelAndView showForm(
      final PortletRequest req,
      @RequestParam(required = false) final String schoolId,
      @RequestParam(required = false) final String formattedCourse,
      @RequestParam(required = false) final String studentUserName,
      @RequestParam(required = false) final String sectionCode,
      @RequestParam(required = false) final String termCode,
      ModelMap model) {
    // Do not use a @ModelAttribute-annotated argument to get the user
    // out of the model b/c Spring will attempt to set properties on it
    // by matching up request param names. This will overwrite user.schoolId
    // with the method param of that name, effectively copying the student's
    // school ID into the faculty user's record.
    if (!StringUtils.isNotBlank(schoolId) && !StringUtils.isNotBlank(studentUserName)) {
      throw new EarlyAlertPortletControllerRuntimeException("Missing student identifier.");
    }

    if (!StringUtils.isNotBlank(formattedCourse) && !StringUtils.isNotBlank(sectionCode)) {
      throw new EarlyAlertPortletControllerRuntimeException("Missing course identifier/s.");
    }
    Person user = (Person) model.get("user");
    if (user == null) {
      throw new EarlyAlertPortletControllerRuntimeException(
          "Missing or deactivated account for current user.");
    }
    FacultyCourse course = null;
    Person student = null;
    ExternalFacultyCourseRoster enrollment = null;
    try {
      // Should really always have a term code (see deprecation notes for
      // getCourseByFacultySchoolIdAndFormattedCourse) but we know at
      // least one real-world deployment (SPC) cannot/does not send term
      // codes when deep linking to the EA form *and* this just happens to
      // work b/c their formattedCourse values are globally unique. So
      // we preserve the option of not filtering by term code.
      course =
          facultyCourseService.getCourseBySearchFacultyCourseTO(
              new SearchFacultyCourseTO(
                  user.getSchoolId(), termCode, sectionCode, formattedCourse));

      if (course == null) {
        throw new EarlyAlertPortletControllerRuntimeException(
            buildErrorMesssage(
                "Course not found or current user is not listed as the instructor of record:",
                user.getSchoolId(),
                schoolId,
                studentUserName,
                formattedCourse,
                termCode,
                sectionCode));
      }

      /*
       * NB:  It's on us to translate from schoolId <-> studentId (SSP
       * UUID) at this point in the Early Alert process.  Previous APIs
       * user the former where following APIs use the later.
       */
      if (StringUtils.isNotBlank(schoolId)) {
        try {
          student = personService.getBySchoolId(schoolId, true); // TODO:  Handle error better??
          if (student == null) {
            throw new EarlyAlertPortletControllerRuntimeException(
                "Student not found by school ID: " + schoolId);
          }
        } catch (ObjectNotFoundException e) {
          throw new EarlyAlertPortletControllerRuntimeException(
              "Student not found by school ID: " + schoolId, e);
        }
      } else {
        try {
          student = personService.getByUsername(studentUserName, true);
          if (student == null) {
            throw new EarlyAlertPortletControllerRuntimeException(
                "Student not found by username: "******"Student not found by username: "******"Selected student has no school ID. Username: "******"Enrollment not found for: ",
                user.getSchoolId(),
                student.getSchoolId(),
                student.getUsername(),
                formattedCourse,
                termCode,
                sectionCode));
      }
    } catch (EarlyAlertPortletControllerRuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new RuntimeException(
          buildErrorMesssage(
              "System error looking up course or enrollment for: ",
              user.getSchoolId(),
              student == null ? schoolId : student.getSchoolId(),
              student == null ? studentUserName : student.getUsername(),
              formattedCourse,
              termCode,
              sectionCode),
          e);
    }
    /*
     *  SANITY CHECK (is this even necessary?  wanted?)
     *    - Confirm that the logged in user is the faculty of record on the
     *      course
     */
    if (!course.getFacultySchoolId().equals(user.getSchoolId())) {
      throw new EarlyAlertPortletControllerRuntimeException(
          buildErrorMesssage(
              "Current user is not listed as the instructor of record on the specified course: ",
              user.getSchoolId(),
              student.getSchoolId(),
              student.getUsername(),
              formattedCourse,
              termCode,
              sectionCode));
    }

    EarlyAlertSearchForm form = new EarlyAlertSearchForm();
    form.setAuthor(user);
    form.setStudent(student);

    form.setSortAndPage(buildSortAndPage(-1, 0));
    PagedResponse<EarlyAlertSearchResultTO> results = earlyAlertService.searchEarlyAlert(form);

    model.put(KEY_STUDENT_ID, student.getId()); // Student UUID
    model.put(KEY_COURSE, course);
    model.put(KEY_ENROLLMENT, enrollment);
    model.put(KEY_EARLY_ALERT_RESULTS, results.getRows());
    try {
      Term term = termService.getByCode(course.getTermCode());
      model.put(KEY_COURSE_TERM_NAME, term.getName());
    } catch (Exception exp) {
      model.put(KEY_COURSE_TERM_NAME, course.getTermCode());
    }

    return new ModelAndView("ea-form", model);
  }
 @Override
 public PagingWrapper<EarlyAlert> getAllForPerson(
     final Person person, final SortingAndPaging sAndP) {
   return getDao().getAllForPersonId(person.getId(), sAndP);
 }