@Override
 public boolean isMember(User user) {
   if (user == null) {
     return false;
   }
   if (user.getPerson().getStudent() != null) {
     final Set<CompetenceCourse> competenceCourses = executionCourse.getCompetenceCourses();
     for (Registration registration : user.getPerson().getStudent().getRegistrationsSet()) {
       // students of any degree sharing the same competence of the given execution course
       for (StudentCurricularPlan studentCurricularPlan :
           registration.getStudentCurricularPlansSet()) {
         for (Enrolment enrolment : studentCurricularPlan.getEnrolmentsSet()) {
           CompetenceCourse competenceCourse =
               enrolment.getCurricularCourse().getCompetenceCourse();
           if (competenceCourses.contains(competenceCourse)) {
             return true;
           }
         }
       }
       // students attending the given execution course (most will be in the previous case but some
       // may not)
       if (registration.getAttendingExecutionCoursesFor().contains(executionCourse)) {
         return true;
       }
     }
   }
   return false;
 }
  public ActionForward setEvaluations(
      ActionMapping mapping,
      ActionForm actionForm,
      HttpServletRequest request,
      HttpServletResponse response) {
    List<List<MarkSheetEnrolmentEvaluationBean>> evaluationsList = getCurriculumEntries();

    StudentCurricularPlan studentCurricularPlan = readStudentCurricularPlan(request);
    ExecutionSemester selectedSemester = readExecutionSemester(request);

    try {
      studentCurricularPlan.setEvaluationsForCurriculumValidation(evaluationsList);

      for (int i = 0; i < evaluationsList.size(); i++) {
        RenderUtils.invalidateViewState("set.evaluations.form." + i);
      }

    } catch (DomainException e) {
      if ("error.grade.invalid.grade".equals(e.getMessage())) {
        addActionMessage("grade-messages", request, "error.invalid.grade");
      } else {
        throw e;
      }
    }

    return prepareSetEvaluations(mapping, actionForm, request, response);
  }
  @Override
  public List<StudentCurricularPlan> getPrecedentStudentCurricularPlans() {
    final Student student = getStudent();
    if (student == null) {
      return Collections.emptyList();
    }

    final List<StudentCurricularPlan> studentCurricularPlans =
        new ArrayList<StudentCurricularPlan>();
    for (final Registration registration : student.getRegistrationsSet()) {

      if (registration.isBolonha()) {
        final StudentCurricularPlan studentCurricularPlan =
            registration.getLastStudentCurricularPlan();

        for (final CycleType cycleType : getValidPrecedentCycleTypes()) {
          if (studentCurricularPlan.hasCycleCurriculumGroup(cycleType)) {
            final CycleCurriculumGroup cycle = studentCurricularPlan.getCycle(cycleType);

            if (!cycle.isConclusionProcessed() && !cycle.isConcluded()) {
              studentCurricularPlans.add(registration.getLastStudentCurricularPlan());
              break;
            }
          }
        }

      } else if (isPreBolonhaPrecedentDegreeAllowed()) {
        if (!registration.isConcluded() && !registration.isRegistrationConclusionProcessed()) {
          studentCurricularPlans.add(registration.getLastStudentCurricularPlan());
        }
      }
    }

    return studentCurricularPlans;
  }
 @Override
 public Grade getEctsGrade(StudentCurricularPlan scp, DateTime processingDate) {
   Grade grade = getGrade();
   Set<Dismissal> dismissals = new HashSet<Dismissal>();
   for (EnrolmentWrapper wrapper : getEnrolmentWrappersSet()) {
     if (wrapper.getCredits().getStudentCurricularPlan().equals(scp)) {
       for (Dismissal dismissal : wrapper.getCredits().getDismissalsSet()) {
         dismissals.add(dismissal);
       }
     }
   }
   Dismissal dismissal = dismissals.iterator().next();
   if (dismissals.size() == 1) {
     if (dismissal instanceof OptionalDismissal || dismissal instanceof CreditsDismissal) {
       return EctsTableIndex.convertGradeToEcts(scp.getDegree(), dismissal, grade, processingDate);
     } else {
       CurricularCourse curricularCourse = dismissal.getCurricularCourse();
       if (curricularCourse != null) {
         return EctsTableIndex.convertGradeToEcts(
             curricularCourse, dismissal, grade, processingDate);
       } else {
         return EctsTableIndex.convertGradeToEcts(
             scp.getDegree(), dismissal, grade, processingDate);
       }
     }
   } else {
     // if more than one exists we can't base the conversion on the
     // origin, so step up to the degree, on a context based on one
     // of the sources.
     return EctsTableIndex.convertGradeToEcts(scp.getDegree(), dismissal, grade, processingDate);
   }
 }
  private List<ExecutionSemester> readPossibleExecutionSemestersForStudentCurricularPlan(
      HttpServletRequest request) {
    StudentCurricularPlan studentCurricularPlan = readStudentCurricularPlan(request);
    final List<ExecutionSemester> executionPeriodsInTimePeriod =
        ExecutionSemester.readExecutionPeriodsInTimePeriod(
            studentCurricularPlan.getStartDate(), getCurrentExecutionSemesterEndDate());

    Collections.sort(
        executionPeriodsInTimePeriod,
        new ReverseComparator(ExecutionSemester.COMPARATOR_BY_SEMESTER_AND_YEAR));
    return executionPeriodsInTimePeriod;
  }
  public ActionForward editEndStageDate(
      ActionMapping mapping,
      ActionForm actionForm,
      HttpServletRequest request,
      HttpServletResponse response) {
    BolonhaStudentEnrollmentBean studentEnrolmentBean = readStudentEnrolmentBean(request);
    StudentCurricularPlan studentCurricularPlan = readStudentCurricularPlan(request);

    studentCurricularPlan.editEndStageDate(studentEnrolmentBean.getEndStageDate());

    return prepareCurriculumValidation(mapping, actionForm, request, response);
  }
  private void createTreeCurriculumModules(
      StudentCurricularPlan studentCurricularPlan,
      ExecutionSemester executionSemester,
      java.util.List<java.util.List<MarkSheetEnrolmentEvaluationBean>> enrolmentEvaluationBeanList,
      java.util.List<java.util.List<MarkSheetEnrolmentEvaluationBean>>
          finalEnrolmentEvaluationBeanList,
      java.util.List<Enrolment> enrolments,
      boolean forEdition) {
    RootCurriculumGroup module = studentCurricularPlan.getRoot();
    enrolments =
        enrolments != null
            ? enrolments
            : new java.util.ArrayList<Enrolment>(module.getEnrolmentsBy(executionSemester));

    for (Enrolment enrolment : enrolments) {
      java.util.List<MarkSheetEnrolmentEvaluationBean> markSheetList =
          new java.util.ArrayList<MarkSheetEnrolmentEvaluationBean>();
      for (EvaluationSeason season :
          EvaluationConfiguration.getInstance().getEvaluationSeasonSet()) {
        markSheetList.add(
            new MarkSheetEnrolmentEvaluationBean(enrolment, executionSemester, season));
      }

      if (enrolment.hasAnyNonTemporaryEvaluations() && !forEdition) {
        finalEnrolmentEvaluationBeanList.add(markSheetList);
      } else {
        enrolmentEvaluationBeanList.add(markSheetList);
      }
    }
  }
  @Atomic
  public static void run(final String studentCurricularPlanId)
      throws DomainException, NonExistingServiceException {
    final StudentCurricularPlan studentCurricularPlan =
        FenixFramework.getDomainObject(studentCurricularPlanId);

    if (studentCurricularPlan != null) {

      for (Enrolment enrolment : studentCurricularPlan.getEnrolmentsSet()) {
        for (EnrolmentEvaluation evaluation : enrolment.getEvaluationsSet()) {
          evaluation.setEnrolmentEvaluationState(EnrolmentEvaluationState.TEMPORARY_OBJ);
        }
      }

      studentCurricularPlan.delete();
    } else {
      throw new NonExistingServiceException();
    }
  }
  protected void putAllStudentsStatisticsInTheRequest(
      HttpServletRequest request,
      List<StudentCurricularPlan> students,
      ExecutionYear currentMonitoringYear) {
    Map<Integer, TutorStatisticsBean> statisticsByApprovedEnrolmentsNumber =
        new HashMap<Integer, TutorStatisticsBean>();

    int maxApprovedEnrolments = 0;

    for (StudentCurricularPlan scp : students) {
      List<Enrolment> enrolments = scp.getEnrolmentsByExecutionYear(currentMonitoringYear);
      int approvedEnrolments = 0;

      for (Enrolment enrolment : enrolments) {
        if (!enrolment.getCurricularCourse().isAnual()
            && enrolment.getEnrollmentState().equals(EnrollmentState.APROVED)) {
          approvedEnrolments++;
        }
      }

      maxApprovedEnrolments = Math.max(maxApprovedEnrolments, approvedEnrolments);

      if (statisticsByApprovedEnrolmentsNumber.containsKey(approvedEnrolments)) {
        TutorStatisticsBean tutorStatisticsbean =
            statisticsByApprovedEnrolmentsNumber.get(approvedEnrolments);
        tutorStatisticsbean.setStudentsNumber(tutorStatisticsbean.getStudentsNumber() + 1);
      } else {
        TutorStatisticsBean tutorStatisticsBean =
            new TutorStatisticsBean(1, approvedEnrolments, students.size());
        tutorStatisticsBean.setApprovedEnrolmentsNumber(approvedEnrolments);
        statisticsByApprovedEnrolmentsNumber.put(approvedEnrolments, tutorStatisticsBean);
      }
    }

    putStatisticsInTheRequest(
        request,
        maxApprovedEnrolments,
        students.size(),
        statisticsByApprovedEnrolmentsNumber,
        "allStudentsStatistics");
  }
  public ActionForward prepareStudentEnrolment(
      ActionMapping mapping,
      ActionForm actionForm,
      HttpServletRequest request,
      HttpServletResponse response) {
    StudentCurricularPlan studentCurricularPlan = readStudentCurricularPlan(request);
    ExecutionSemester executionSemester = readExecutionSemester(request);

    addDebtsWarningMessages(
        studentCurricularPlan.getRegistration().getStudent(), executionSemester, request);

    request.setAttribute(
        "bolonhaStudentEnrollmentBean",
        readBolonhaStudentEnrollmentBean(
            request,
            studentCurricularPlan,
            executionSemester,
            null,
            CurricularRuleLevel.ENROLMENT_NO_RULES,
            true));

    return mapping.findForward("show-degree-modules-to-enrol");
  }
  public ActionForward editEvaluations(
      ActionMapping mapping,
      ActionForm actionForm,
      HttpServletRequest request,
      HttpServletResponse response) {
    try {
      List<List<MarkSheetEnrolmentEvaluationBean>> evaluationsList = getCurriculumEntries();

      StudentCurricularPlan studentCurricularPlan = readStudentCurricularPlan(request);

      ExecutionSemester executionSemester = readExecutionSemester(request);
      studentCurricularPlan.setEvaluationsForCurriculumValidation(evaluationsList);

      return prepareSetEvaluations(mapping, actionForm, request, response);
    } catch (DomainException e) {
      if ("error.grade.invalid.grade".equals(e.getMessage())) {
        addActionMessage("grade-messages", request, "error.invalid.grade");

        return prepareEditEvaluation(mapping, actionForm, request, response);
      }

      throw e;
    }
  }
  public ActionForward warmUpCacheForEnrolmentPeriodStart(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    final ExecutionSemester ces = ExecutionSemester.readActualExecutionSemester();
    final ExecutionSemester pes = ces == null ? null : ces.getPreviousExecutionPeriod();

    if (ces != null && pes != null) {
      long s = System.currentTimeMillis();
      for (final ExecutionCourse executionCourse : ces.getAssociatedExecutionCoursesSet()) {
        executionCourse.getName();
        for (final CourseLoad courseLoad : executionCourse.getCourseLoadsSet()) {
          courseLoad.getType();
          for (final Shift shift : courseLoad.getShiftsSet()) {
            shift.getNome();
            for (final SchoolClass schoolClass : shift.getAssociatedClassesSet()) {
              schoolClass.getNome();
              final ExecutionDegree executionDegree = schoolClass.getExecutionDegree();
              final DegreeCurricularPlan degreeCurricularPlan =
                  executionDegree.getDegreeCurricularPlan();
              degreeCurricularPlan.getName();
              final Degree degree = degreeCurricularPlan.getDegree();
              degree.getDegreeType();
              final RootCourseGroup root = degreeCurricularPlan.getRoot();
              load(root);
            }
            for (final Lesson lesson : shift.getAssociatedLessonsSet()) {
              lesson.getBeginHourMinuteSecond();
              for (OccupationPeriod period = lesson.getPeriod();
                  period != null;
                  period = period.getNextPeriod()) {
                period.getStartDate();
              }
              for (final LessonInstance lessonInstance : lesson.getLessonInstancesSet()) {
                lessonInstance.getBeginDateTime();
              }
            }
          }
        }
      }
      long e = System.currentTimeMillis();
      logger.info(
          "Warming up cache for enrolment period. Load of current semester information took {}ms.",
          e - s);

      s = System.currentTimeMillis();
      //            for (final RoomClassification roomClassification :
      // rootDomainObject.getRoomClassificationSet()) {
      //                for (final RoomInformation roomInformation :
      // roomClassification.getRoomInformationsSet()) {
      //                    roomInformation.getDescription();
      //                    final Room room = roomInformation.getRoom();
      //                    room.getNormalCapacity();
      //                }
      //            }
      e = System.currentTimeMillis();
      logger.info("Warming up cache for enrolment period. Load of room listing took {}ms.", e - s);

      final Set<Student> students = new HashSet<Student>();
      s = System.currentTimeMillis();
      for (final Enrolment enrolment : pes.getEnrolmentsSet()) {
        students.add(enrolment.getStudent());
      }
      e = System.currentTimeMillis();
      logger.info("Warming up cache for enrolment period. Search for students took {}ms.", e - s);

      s = System.currentTimeMillis();
      for (final Student student : students) {
        student.getNumber();
        for (final Registration registration : student.getRegistrationsSet()) {
          registration.getNumber();
          for (final StudentCurricularPlan studentCurricularPlan :
              registration.getStudentCurricularPlansSet()) {
            final RootCurriculumGroup root = studentCurricularPlan.getRoot();
            load(root);
          }
        }
      }
      e = System.currentTimeMillis();
      logger.info(
          "Warming up cache for enrolment period. Load of student curriculum took {}ms.", e - s);
    }

    return monitor(mapping, form, request, response);
  }