@Override
 @SuppressWarnings("unchecked")
 public void onCloseCourse(Course course) throws SystemException {
   for (CourseResult courseResult :
       (List<CourseResult>)
           CourseResultLocalServiceUtil.dynamicQuery(
               CourseResultLocalServiceUtil.dynamicQuery()
                   .add(PropertyFactoryUtil.forName("courseId").eq(course.getCourseId()))
                   .add(PropertyFactoryUtil.forName("passedDate").isNull()))) {
     courseResult.setPassedDate(course.getModifiedDate());
     CourseResultLocalServiceUtil.update(courseResult);
   }
 }
 @Override
 public void setEvaluationModel(Course course, JSONObject model)
     throws PortalException, SystemException, DocumentException, IOException {
   Document document = SAXReaderUtil.createDocument();
   Element rootElement = document.addElement("eval");
   rootElement.addElement("courseEval").setText(PonderatedCourseEval.class.getName());
   course.setCourseExtraData(document.formattedString());
 }
  @Override
  public boolean updateCourse(Course course) throws SystemException {
    try {
      for (User userOfCourse : UserLocalServiceUtil.getGroupUsers(course.getGroupCreatedId())) {
        if (!PermissionCheckerFactoryUtil.create(userOfCourse)
            .hasPermission(
                course.getGroupCreatedId(),
                "com.liferay.lms.model",
                course.getGroupCreatedId(),
                "VIEW_RESULTS")) {
          updateCourse(course, userOfCourse.getUserId());
        }
      }

      return true;
    } catch (Exception e) {
      throw new SystemException(e);
    }
  }
 public static java.util.List<Long> getRequiredActivities(Course course)
     throws DocumentException, PortalException, SystemException {
   java.util.List<Long> result = new java.util.ArrayList<Long>();
   String extraData = course.getCourseExtraData();
   if (extraData != null && extraData.startsWith("<?xml")) {
     Document document = SAXReaderUtil.read(extraData);
     Element rootElement = document.getRootElement();
     java.util.List<Element> reqElements = rootElement.elements("required");
     for (Element reqElement : reqElements) {
       long actId = Long.parseLong(reqElement.attributeValue("actId"));
       LearningActivity larn = LearningActivityLocalServiceUtil.fetchLearningActivity(actId);
       if (larn != null
           && larn.getGroupId() == course.getGroupCreatedId()
           && larn.getWeightinmodule() > 0) {
         result.add(actId);
       }
     }
   }
   return result;
 }
 public static long getScore(Course course)
     throws DocumentException, PortalException, SystemException {
   long score = 0;
   String extraData = course.getCourseExtraData();
   if (extraData != null && extraData.startsWith("<?xml")) {
     Document document = SAXReaderUtil.read(extraData);
     Element rootElement = document.getRootElement();
     Element scoreElement = rootElement.element("score");
     if (scoreElement != null) {
       score = Long.valueOf(scoreElement.attributeValue("value"));
     }
   }
   return score;
 }
  @Override
  public boolean updateCourse(Course course, long userId) throws SystemException {

    CourseResult courseResult =
        CourseResultLocalServiceUtil.getByUserAndCourse(course.getCourseId(), userId);
    // .fetchByuc(mresult.getUserId(), course.getCourseId());
    if (courseResult == null) {
      courseResult = CourseResultLocalServiceUtil.create(course.getCourseId(), userId);
    }

    if (courseResult.getStartDate() == null) {
      courseResult.setStartDate(new Date());
    }

    try {
      java.util.Map<Long, Long> weights = PonderatedCourseEval.getActivitiesWeight(course);
      long score = PonderatedCourseEval.getScore(course);

      boolean passed = true;
      long result = 0;
      long weight = 0;
      List<LearningActivity> learningActivities =
          LearningActivityLocalServiceUtil.getMandatoryLearningActivitiesOfGroup(
              course.getGroupCreatedId());

      // Guardo los resultados de las actividades del usuario en el curso en un hashmap para no
      // tener que acceder a bbdd por cada uno de ellos
      List<LearningActivityResult> lresult =
          LearningActivityResultLocalServiceUtil.getMandatoryByGroupIdUserId(
              course.getGroupCreatedId(), userId);
      HashMap<Long, LearningActivityResult> results = new HashMap<Long, LearningActivityResult>();
      for (LearningActivityResult ar : lresult) {
        results.put(ar.getActId(), ar);
      }

      boolean isFailed = false;
      LearningActivityResult learningActivityResult = null;

      for (LearningActivity act : learningActivities) {

        if (!weights.containsKey(
            act
                .getActId())) { // Solo se tienen en cuenta las actividades obligatorias que tienen
                                // peso definido
          continue;
        }

        if (results.containsKey(act.getActId())) {
          learningActivityResult = results.get(act.getActId());
        } else {
          learningActivityResult = null;
        }

        if (learningActivityResult != null) {
          if (learningActivityResult.getEndDate() != null) {
            if (!learningActivityResult.isPassed()) {
              passed = false;
              if (act.getTries() > 0) {
                long userTries =
                    LearningActivityTryLocalServiceUtil.getLearningActivityTryByActUserCount(
                        act.getActId(), userId);
                if (userTries >= act.getTries()) {
                  isFailed = true;
                }
              }
            }
            result = result + (learningActivityResult.getResult() * weights.get(act.getActId()));

          } else {
            passed = false;
          }
        } else {
          passed = false;
        }
        weight += weights.get(act.getActId());
      }

      if (result > 0 && weight > 0) {
        result = result / weight;
      }

      if (result < score) {
        passed = false;
      }

      // Si el usuario se ha marcado como isFailed es porque lo tiene suspenso. Se le asigna un
      // passed a false y se marca la fecha de finalización del curso (passedDate).
      courseResult.setPassed(passed && !isFailed);
      // Se almacena el result del resultado del usuario en el curso.
      courseResult.setResult(result);
      if ((passed || isFailed) && courseResult.getPassedDate() == null) {
        courseResult.setPassedDate(new Date());
      }
      CourseResultLocalServiceUtil.update(courseResult);
      return true;

    } catch (PortalException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (DocumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return true;
  }
  public void doView(RenderRequest renderRequest, RenderResponse renderResponse)
      throws IOException, PortletException {
    ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
    try {

      log.debug(":: VIEW STUDENT SEARCH " + this.viewJSP);

      PortletPreferences preferences = renderRequest.getPreferences();
      boolean showSearcher =
          GetterUtil.getBoolean(preferences.getValue("showSearcher", StringPool.TRUE));
      boolean showScreenName =
          GetterUtil.getBoolean(preferences.getValue("showScreenName", StringPool.TRUE));
      boolean showEmail =
          GetterUtil.getBoolean(preferences.getValue("showEmail", StringPool.FALSE));

      long teamId = ParamUtil.getLong(renderRequest, "team", 0);

      List<Team> teams = TeamLocalServiceUtil.getGroupTeams(themeDisplay.getScopeGroupId());

      renderRequest.setAttribute("showSearcher", showSearcher);
      renderRequest.setAttribute("showScreenName", showScreenName);
      renderRequest.setAttribute("showEmail", showEmail);

      PortletURL iteratorURL = renderResponse.createRenderURL();
      iteratorURL.setParameter("team", String.valueOf(teamId));

      /*iteratorURL.setParameter("showSearcher" ,  String.valueOf(showSearcher));
      iteratorURL.setParameter("showScreenName" , String.valueOf(showScreenName));
      iteratorURL.setParameter("showEmail" ,  String.valueOf(showEmail));*/

      UserSearchContainer userSearchContainer = new UserSearchContainer(renderRequest, iteratorURL);
      UserDisplayTerms displayTerms = (UserDisplayTerms) userSearchContainer.getDisplayTerms();
      LinkedHashMap<String, Object> params = new LinkedHashMap<String, Object>();
      params.put("usersGroups", new Long(themeDisplay.getScopeGroupId()));

      Course course = CourseLocalServiceUtil.fetchByGroupCreatedId(themeDisplay.getScopeGroupId());

      if (log.isDebugEnabled()) {
        log.debug("NAME " + displayTerms.getFirstName());
        log.debug("SURNAME " + displayTerms.getLastName());
        log.debug("SCREEN NAME " + displayTerms.getScreenName());
        log.debug("EMAIL ADDRESS " + displayTerms.getEmailAddress());
        log.debug("KEYWORDS " + displayTerms.getKeywords());
        log.debug("START " + userSearchContainer.getStart());
        log.debug("END  " + userSearchContainer.getEnd());

        log.debug("ADVANCED SEARCH " + displayTerms.isAdvancedSearch());
        log.debug("AND OPERATOR " + displayTerms.isAndOperator());
        log.debug("TEAM " + teamId);
      }

      if (log.isDebugEnabled()) {
        log.debug("NAME " + ParamUtil.getString(renderRequest, "firstName"));
      }

      if (course != null) {
        try {
          if (displayTerms.isAdvancedSearch()) {
            userSearchContainer.setResults(
                CourseLocalServiceUtil.getStudentsFromCourse(
                    themeDisplay.getCompanyId(),
                    themeDisplay.getScopeGroupId(),
                    userSearchContainer.getStart(),
                    userSearchContainer.getEnd(),
                    teamId,
                    displayTerms.getFirstName(),
                    displayTerms.getLastName(),
                    displayTerms.getScreenName(),
                    displayTerms.getEmailAddress(),
                    displayTerms.isAndOperator()));

            userSearchContainer.setTotal(
                CourseLocalServiceUtil.getStudentsFromCourseCount(
                    course.getCourseId(),
                    teamId,
                    displayTerms.getFirstName(),
                    displayTerms.getLastName(),
                    displayTerms.getScreenName(),
                    displayTerms.getEmailAddress(),
                    displayTerms.isAndOperator()));

          } else {
            userSearchContainer.setResults(
                CourseLocalServiceUtil.getStudentsFromCourse(
                    themeDisplay.getCompanyId(),
                    themeDisplay.getScopeGroupId(),
                    userSearchContainer.getStart(),
                    userSearchContainer.getEnd(),
                    teamId,
                    displayTerms.getKeywords(),
                    displayTerms.getKeywords(),
                    displayTerms.getKeywords(),
                    displayTerms.getKeywords(),
                    true));

            userSearchContainer.setTotal(
                CourseLocalServiceUtil.getStudentsFromCourseCount(
                    course.getCourseId(),
                    teamId,
                    displayTerms.getKeywords(),
                    displayTerms.getKeywords(),
                    displayTerms.getKeywords(),
                    displayTerms.getKeywords(),
                    true));
          }

        } catch (SystemException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      if (log.isDebugEnabled()) {
        log.debug(" -- TOTAL: " + userSearchContainer.getTotal());
        log.debug(" -- SIZE: " + userSearchContainer.getResults().size());
      }

      renderRequest.setAttribute("searchContainer", userSearchContainer);
      renderRequest.setAttribute("team", teamId);
      renderRequest.setAttribute("teams", teams);

    } catch (SystemException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (PortalException e) {
      // TODO: handle exception
      e.printStackTrace();
    }

    this.include(this.viewJSP, renderRequest, renderResponse);
  }