/** Used by to task executor, without any GUI */
  @Override
  public void run() {
    final List<BulkAssessmentFeedback> feedbacks = new ArrayList<>();
    try {
      log.audit("Start process bulk assessment");

      LoggingResourceable[] infos = new LoggingResourceable[2];
      if (task != null && task.getCreator() != null) {
        UserSession session = new UserSession();
        session.setIdentity(task.getCreator());
        session.setSessionInfo(
            new SessionInfo(task.getCreator().getKey(), task.getCreator().getName()));
        ThreadLocalUserActivityLoggerInstaller.initUserActivityLogger(session);
        infos[0] = LoggingResourceable.wrap(courseRes, OlatResourceableType.course);
        ThreadLocalUserActivityLogger.addLoggingResourceInfo(infos[0]);
        infos[1] = LoggingResourceable.wrap(getCourseNode());
        ThreadLocalUserActivityLogger.addLoggingResourceInfo(infos[1]);
      }

      doProcess(feedbacks);
      log.audit("End process bulk assessment");
      cleanup();

      ThreadLocalUserActivityLogger.log(AssessmentLoggingAction.ASSESSMENT_BULK, getClass(), infos);
    } catch (Exception e) {
      log.error("", e);
      feedbacks.add(new BulkAssessmentFeedback("", "bulk.assessment.error"));
      throw e;
    } finally {
      cleanupUnzip();
      sendFeedback(feedbacks);
    }
  }
  @Override
  public boolean isInterceptionRequired(UserRequest ureq) {
    UserSession usess = ureq.getUserSession();

    boolean interception = false;
    if (isREST(ureq)) {
      // do nothing
    } else if (!historyModule.isResumeEnabled()) {
      String bc = getLandingBC(ureq);
      launch(ureq, bc);
    } else if (usess.getRoles().isGuestOnly()) {
      String bc = getLandingBC(ureq);
      launch(ureq, bc);
    } else {
      Preferences prefs = usess.getGuiPreferences();
      String resumePrefs = (String) prefs.get(WindowManager.class, "resume-prefs");
      if (!StringHelper.containsNonWhitespace(resumePrefs)) {
        resumePrefs = historyModule.getResumeDefaultSetting();
      }

      if ("none".equals(resumePrefs)) {
        String bc = getLandingBC(ureq);
        launch(ureq, bc);
      } else if ("auto".equals(resumePrefs)) {
        HistoryPoint historyEntry =
            HistoryManager.getInstance().readHistoryPoint(ureq.getIdentity());
        if (historyEntry != null
            && StringHelper.containsNonWhitespace(historyEntry.getBusinessPath())) {
          List<ContextEntry> cloneCes =
              BusinessControlFactory.getInstance().cloneContextEntries(historyEntry.getEntries());
          BusinessControl bc =
              BusinessControlFactory.getInstance().createFromContextEntries(cloneCes);
          launch(ureq, bc);
        } else {
          String bc = getLandingBC(ureq);
          launch(ureq, bc);
        }
      } else if ("ondemand".equals(resumePrefs)) {
        HistoryPoint historyEntry = historyManager.readHistoryPoint(ureq.getIdentity());
        if (historyEntry != null
            && StringHelper.containsNonWhitespace(historyEntry.getBusinessPath())) {
          interception = true;

          String bc = getLandingBC(ureq);
          if (StringHelper.containsNonWhitespace(bc)) {
            noButton.setVisible(false);
          } else {
            landingButton.setVisible(false);
          }
        } else {
          String bc = getLandingBC(ureq);
          launch(ureq, bc);
        }
      }
    }
    return interception;
  }
  private SessionsVO getSessionsVO() {
    SessionsVO vo = new SessionsVO();

    SessionStatsManager sessionStatsManager = CoreSpringFactory.getImpl(SessionStatsManager.class);
    UserSessionManager sessionManager = CoreSpringFactory.getImpl(UserSessionManager.class);
    vo.setCount(sessionManager.getUserSessionsCnt());

    Set<UserSession> userSessions = sessionManager.getAuthenticatedUserSessions();
    int webdavcount = 0;
    int secureWebdavCount = 0;
    int authenticatedcount = 0;
    int secureAuthenticatedCount = 0;
    int restCount = 0;
    int secureRestCount = 0;
    for (UserSession usess : userSessions) {
      SessionInfo sessInfo = usess.getSessionInfo();
      if (sessInfo.isWebDAV()) {
        webdavcount++;
        if (sessInfo.isSecure()) {
          secureWebdavCount++;
        }
      } else if (sessInfo.isREST()) {
        restCount++;
        if (sessInfo.isSecure()) {
          secureRestCount++;
        }
      } else {
        authenticatedcount++;
        if (sessInfo.isSecure()) {
          secureAuthenticatedCount++;
        }
      }
    }

    vo.setAuthenticatedCount(authenticatedcount);
    vo.setSecureAuthenticatedCount(secureAuthenticatedCount);
    vo.setWebdavCount(webdavcount);
    vo.setSecureWebdavCount(secureWebdavCount);
    vo.setRestCount(restCount);
    vo.setSecureRestCount(secureRestCount);
    // Instant messaging
    vo.setInstantMessagingCount(-1);

    SessionsStats statsLastMinute = sessionStatsManager.getSessionsStatsLast(60);
    SessionsStats statsLast5Minutes = sessionStatsManager.getSessionsStatsLast(300);
    vo.setAuthenticatedClickCountLastMinute(statsLastMinute.getAuthenticatedClickCalls());
    vo.setAuthenticatedClickCountLastFiveMinutes(statsLast5Minutes.getAuthenticatedPollerCalls());
    vo.setAuthenticatedPollCountLastMinute(statsLastMinute.getAuthenticatedPollerCalls());
    vo.setAuthenticatedPollCountLastFiveMinutes(statsLast5Minutes.getAuthenticatedPollerCalls());
    vo.setRequestLastMinute(statsLastMinute.getRequests());
    vo.setRequestLastFiveMinutes(statsLast5Minutes.getRequests());
    vo.setConcurrentDispatchThreads(sessionStatsManager.getConcurrentCounter());
    return vo;
  }
  /**
   * @see
   *     org.olat.core.commons.services.webdav.WebDAVManager#handleAuthentication(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse)
   */
  @Override
  public boolean handleAuthentication(HttpServletRequest req, HttpServletResponse resp) {
    UserSession usess = sessionManager.getUserSession(req);
    if (usess != null && usess.isAuthenticated()) {
      req.setAttribute(REQUEST_USERSESSION_KEY, usess);
      return true;
    }

    usess = doAuthentication(req, resp);
    if (usess == null) {
      return false;
    }

    // register usersession in REQUEST, not session !!
    // see SecureWebDAVServlet.setAuthor() and checkQuota()
    req.setAttribute(REQUEST_USERSESSION_KEY, usess);
    return true;
  }
  private UserSession afterAuthorization(Identity identity, HttpServletRequest request) {
    UserSession usess = sessionManager.getUserSession(request);
    synchronized (usess) {
      // double check to prevent severals concurrent login
      if (usess.isAuthenticated()) {
        return usess;
      }

      sessionManager.signOffAndClear(usess);
      usess.setIdentity(identity);
      UserDeletionManager.getInstance().setIdentityAsActiv(identity);
      // set the roles (admin, author, guest)
      Roles roles = BaseSecurityManager.getInstance().getRoles(identity);
      usess.setRoles(roles);
      // set session info
      SessionInfo sinfo =
          new SessionInfo(identity.getKey(), identity.getName(), request.getSession());
      User usr = identity.getUser();
      sinfo.setFirstname(usr.getProperty(UserConstants.FIRSTNAME, null));
      sinfo.setLastname(usr.getProperty(UserConstants.LASTNAME, null));

      String remoteAddr = request.getRemoteAddr();
      sinfo.setFromIP(remoteAddr);
      sinfo.setFromFQN(remoteAddr);
      try {
        InetAddress[] iaddr = InetAddress.getAllByName(request.getRemoteAddr());
        if (iaddr.length > 0) sinfo.setFromFQN(iaddr[0].getHostName());
      } catch (UnknownHostException e) {
        // ok, already set IP as FQDN
      }
      sinfo.setAuthProvider(BaseSecurityModule.getDefaultAuthProviderIdentifier());
      sinfo.setUserAgent(request.getHeader("User-Agent"));
      sinfo.setSecure(request.isSecure());
      sinfo.setWebDAV(true);
      sinfo.setWebModeFromUreq(null);
      // set session info for this session
      usess.setSessionInfo(sinfo);
      //
      sessionManager.signOn(usess);
      return usess;
    }
  }
  @Override
  public WebResourceRoot getWebDAVRoot(HttpServletRequest req) {
    UserSession usess = getUserSession(req);
    if (usess == null || usess.getIdentity() == null) {
      return createEmptyRoot(usess);
    }

    usess.getSessionInfo().setLastClickTime();
    VFSResourceRoot fdc = (VFSResourceRoot) usess.getEntry("_DIRCTX");
    if (fdc != null) {
      return fdc;
    }

    IdentityEnvironment identityEnv = usess.getIdentityEnvironment();
    VFSContainer webdavContainer = getMountableRoot(identityEnv);

    // create the / folder
    VirtualContainer rootContainer = new VirtualContainer("");
    rootContainer.addItem(webdavContainer);
    rootContainer.setLocalSecurityCallback(new ReadOnlyCallback());

    fdc = new VFSResourceRoot(identityEnv.getIdentity(), rootContainer);
    usess.putEntry("_DIRCTX", fdc);
    return fdc;
  }
 private WebResourceRoot createEmptyRoot(UserSession usess) {
   // create the / folder
   VirtualContainer rootContainer = new VirtualContainer("");
   rootContainer.setLocalSecurityCallback(new ReadOnlyCallback());
   return new VFSResourceRoot(usess.getIdentity(), rootContainer);
 }
  /**
   * @see org.olat.core.gui.control.DefaultController#event(org.olat.core.gui.UserRequest,
   *     org.olat.core.gui.control.Controller, org.olat.core.gui.control.Event)
   */
  @Override
  public void event(UserRequest ureq, Controller source, Event event) {
    if (source == loginForm && event == Event.DONE_EVENT) {
      String login = loginForm.getLogin();
      String pass = loginForm.getPass();
      if (loginModule.isLoginBlocked(login)) {
        // do not proceed when blocked
        showError("login.blocked", loginModule.getAttackPreventionTimeoutMin().toString());
        getLogger()
            .audit(
                "Login attempt on already blocked login for "
                    + login
                    + ". IP::"
                    + ureq.getHttpReq().getRemoteAddr(),
                null);
        return;
      }
      authenticatedIdentity = olatAuthenticationSpi.authenticate(null, login, pass);
      if (authenticatedIdentity == null) {
        if (loginModule.registerFailedLoginAttempt(login)) {
          getLogger()
              .audit(
                  "Too many failed login attempts for "
                      + login
                      + ". Login blocked. IP::"
                      + ureq.getHttpReq().getRemoteAddr(),
                  null);
          showError("login.blocked", loginModule.getAttackPreventionTimeoutMin().toString());
          return;
        } else {
          showError("login.error", WebappHelper.getMailConfig("mailReplyTo"));
          return;
        }
      } else {
        try {
          String language = authenticatedIdentity.getUser().getPreferences().getLanguage();
          UserSession usess = ureq.getUserSession();
          if (StringHelper.containsNonWhitespace(language)) {
            usess.setLocale(I18nManager.getInstance().getLocaleOrDefault(language));
          }
        } catch (Exception e) {
          logError("Cannot set the user language", e);
        }
      }

      loginModule.clearFailedLoginAttempts(login);

      // Check if disclaimer has been accepted
      if (registrationManager.needsToConfirmDisclaimer(authenticatedIdentity)) {
        // accept disclaimer first

        removeAsListenerAndDispose(disclaimerCtr);
        disclaimerCtr = new DisclaimerController(ureq, getWindowControl());
        listenTo(disclaimerCtr);

        removeAsListenerAndDispose(cmc);
        cmc =
            new CloseableModalController(
                getWindowControl(), translate("close"), disclaimerCtr.getInitialComponent());
        listenTo(cmc);

        cmc.activate();

      } else {
        // disclaimer acceptance not required
        authenticated(ureq, authenticatedIdentity);
      }
    } else if (source == disclaimerCtr) {
      cmc.deactivate();
      if (event == Event.DONE_EVENT) {
        // disclaimer accepted
        registrationManager.setHasConfirmedDislaimer(authenticatedIdentity);
        authenticated(ureq, authenticatedIdentity);
      }
    } else if (cmc == source) {
      cleanUp();
    }
    if (source == subController) {
      if (event == Event.CANCELLED_EVENT) {
        cmc.deactivate();
        cleanUp();
      }
    }
  }
 private boolean isREST(UserRequest ureq) {
   UserSession usess = ureq.getUserSession();
   if (usess.getEntry("AuthDispatcher:businessPath") != null) return true;
   if (usess.getEntry("AuthDispatcher:entryUrl") != null) return true;
   return false;
 }