/**
   * All requests are handled by this handleRequest method. In case of SAMLRequest the user will be
   * redirected to commonAuth servlet for authentication. Based on successful authentication of the
   * user a SAMLResponse is sent back to service provider. In case of logout requests, the IDP will
   * send logout requests to the other session participants and then send the logout response back
   * to the initiator.
   *
   * @param req
   * @param resp
   * @throws ServletException
   * @throws IOException
   */
  private void handleRequest(HttpServletRequest req, HttpServletResponse resp, boolean isPost)
      throws ServletException, IOException {
    String sessionId = null;
    Cookie ssoTokenIdCookie = getTokenIdCookie(req);

    if (ssoTokenIdCookie != null) {
      sessionId = ssoTokenIdCookie.getValue();
    }

    String queryString = req.getQueryString();
    if (log.isDebugEnabled()) {
      log.debug("Query string : " + queryString);
    }
    // if an openid authentication or password authentication
    String authMode = CharacterEncoder.getSafeText(req.getParameter("authMode"));
    if (!SAMLSSOConstants.AuthnModes.OPENID.equals(authMode)) {
      authMode = SAMLSSOConstants.AuthnModes.USERNAME_PASSWORD;
    }
    String relayState =
        CharacterEncoder.getSafeText(req.getParameter(SAMLSSOConstants.RELAY_STATE));
    String spEntityID =
        CharacterEncoder.getSafeText(
            req.getParameter(SAMLSSOConstants.QueryParameter.SP_ENTITY_ID.toString()));
    String samlRequest = CharacterEncoder.getSafeText(req.getParameter("SAMLRequest"));
    String sessionDataKey = CharacterEncoder.getSafeText(req.getParameter("sessionDataKey"));
    String slo =
        CharacterEncoder.getSafeText(
            req.getParameter(SAMLSSOConstants.QueryParameter.SLO.toString()));

    boolean isExpFired = false;
    try {

      String tenantDomain = CharacterEncoder.getSafeText(req.getParameter("tenantDomain"));
      SAMLSSOUtil.setTenantDomainInThreadLocal(tenantDomain);

      if (sessionDataKey != null) { // Response from common authentication framework.
        SAMLSSOSessionDTO sessionDTO = getSessionDataFromCache(sessionDataKey);

        if (sessionDTO != null) {
          SAMLSSOUtil.setTenantDomainInThreadLocal(sessionDTO.getTenantDomain());
          if (sessionDTO.isInvalidLogout()) {
            log.warn("Redirecting to default logout page due to an invalid logout request");
            String serverUrl = CarbonUIUtil.getAdminConsoleURL(req);
            resp.sendRedirect(
                serverUrl.replace(
                    SAMLSSOConstants.SAML_ENDPOINT, SAMLSSOConstants.DEFAULT_LOGOUT_LOCATION));
          } else if (sessionDTO.isLogoutReq()) {
            handleLogoutResponseFromFramework(req, resp, sessionDTO);
          } else {
            handleAuthenticationReponseFromFramework(req, resp, sessionId, sessionDTO);
          }

          removeAuthenticationResultFromCache(sessionDataKey);

        } else {
          log.error("Failed to retrieve sessionDTO from the cache for key " + sessionDataKey);
          String errorResp =
              SAMLSSOUtil.buildErrorResponse(
                  SAMLSSOConstants.StatusCodes.IDENTITY_PROVIDER_ERROR,
                  SAMLSSOConstants.Notification.EXCEPTION_STATUS,
                  null);
          sendNotification(
              errorResp,
              SAMLSSOConstants.Notification.EXCEPTION_STATUS,
              SAMLSSOConstants.Notification.EXCEPTION_MESSAGE,
              null,
              req,
              resp);
          return;
        }
      } else if (spEntityID != null || slo != null) { // idp initiated SSO/SLO
        handleIdPInitSSO(
            req, resp, relayState, queryString, authMode, sessionId, isPost, (slo != null));
      } else if (samlRequest != null) { // SAMLRequest received. SP initiated SSO
        handleSPInitSSO(
            req, resp, queryString, relayState, authMode, samlRequest, sessionId, isPost);
      } else {
        log.debug("Invalid request message or single logout message ");

        if (sessionId == null) {
          String errorResp =
              SAMLSSOUtil.buildErrorResponse(
                  SAMLSSOConstants.StatusCodes.REQUESTOR_ERROR, "Invalid request message", null);
          sendNotification(
              errorResp,
              SAMLSSOConstants.Notification.INVALID_MESSAGE_STATUS,
              SAMLSSOConstants.Notification.INVALID_MESSAGE_MESSAGE,
              null,
              req,
              resp);
        } else {
          // Non-SAML request are assumed to be logout requests
          sendToFrameworkForLogout(req, resp, null, null, sessionId, true, false);
        }
      }
    } catch (UserStoreException e) {
      if (log.isDebugEnabled()) {
        log.debug("Error occurred while handling SAML2 SSO request", e);
      }
      String errorResp = null;
      try {
        errorResp =
            SAMLSSOUtil.buildErrorResponse(
                SAMLSSOConstants.StatusCodes.IDENTITY_PROVIDER_ERROR,
                "Error occurred while handling SAML2 SSO request",
                null);
      } catch (IdentityException e1) {
        log.error("Error while building SAML response", e1);
      }
      sendNotification(
          errorResp,
          SAMLSSOConstants.Notification.EXCEPTION_STATUS,
          SAMLSSOConstants.Notification.EXCEPTION_MESSAGE,
          null,
          req,
          resp);
    } catch (IdentityException e) {
      log.error("Error when processing the authentication request!", e);
      String errorResp = null;
      try {
        errorResp =
            SAMLSSOUtil.buildErrorResponse(
                SAMLSSOConstants.StatusCodes.IDENTITY_PROVIDER_ERROR,
                "Error when processing the authentication request",
                null);
      } catch (IdentityException e1) {
        log.error("Error while building SAML response", e1);
      }
      sendNotification(
          errorResp,
          SAMLSSOConstants.Notification.EXCEPTION_STATUS,
          SAMLSSOConstants.Notification.EXCEPTION_MESSAGE,
          null,
          req,
          resp);
    }
  }