@SuppressWarnings("unchecked")
  protected void processRequest(HttpServletRequest req, HttpServletResponse resp, boolean isPost)
      throws ServletException, IOException {
    ServerManager manager = getServerManager();
    IWMainApplication iwma = IWMainApplication.getIWMainApplication(req);

    // extract the parameters from the request
    ParameterList requestParameters = new ParameterList(req.getParameterMap());

    OpenIDServerBean serverBean = ELUtil.getInstance().getBean("openIDServerBean");
    ParameterList sessionStoredParameterList = serverBean.getParameterList();
    if (sessionStoredParameterList != null) {
      if (!requestParameters.hasParameter(OpenIDConstants.PARAMETER_OPENID_MODE)) {
        sessionStoredParameterList.addParams(requestParameters);
        requestParameters = sessionStoredParameterList;
      }
    }

    String mode =
        requestParameters.hasParameter(OpenIDConstants.PARAMETER_OPENID_MODE)
            ? requestParameters.getParameterValue(OpenIDConstants.PARAMETER_OPENID_MODE)
            : null;
    String realm =
        requestParameters.hasParameter(OpenIDConstants.PARAMETER_REALM)
            ? requestParameters.getParameterValue(OpenIDConstants.PARAMETER_REALM)
            : null;
    if (realm != null) {
      serverBean.setReturnUrl(realm);
      realm = getRealmName(realm);
      serverBean.setRealm(realm);
    }

    Message response;
    String responseText = null;

    try {
      if (OpenIDConstants.PARAMETER_ASSOCIATE.equals(mode)) {
        // --- process an association request ---
        response = manager.associationResponse(requestParameters);
        responseText = response.keyValueFormEncoding();
      } else if (OpenIDConstants.PARAMETER_CHECKID_SETUP.equals(mode)
          || OpenIDConstants.PARAMETER_CHECKID_IMMEDIATE.equals(mode)) {
        IWContext iwc = new IWContext(req, resp, getServletContext());

        boolean goToLogin = doRedirectToLoginPage(manager, requestParameters, iwc, realm);

        if (!goToLogin) {
          serverBean.setParameterList(null);
          serverBean.setServerUrl(null);
          serverBean.setDoRedirect(null);
          serverBean.setUsername(null);

          // interact with the user and obtain data needed to continue
          User user = iwc.getCurrentUser();
          String userSelectedClaimedId = getUserSelectedClaimedId(iwc, user);

          // --- process an authentication request ---
          AuthRequest authReq =
              AuthRequest.createAuthRequest(requestParameters, manager.getRealmVerifier());

          storeRequestedAttributesToSession(iwc, authReq);

          Boolean authenticatedAndApproved = isAuthenticatedAndApproved(iwc, user, authReq);

          String opLocalId = null;
          // if the user chose a different claimed_id than the one in request
          if (userSelectedClaimedId != null
              && !userSelectedClaimedId.equals(authReq.getClaimed())) {
            opLocalId = userSelectedClaimedId;
          }

          response =
              manager.authResponse(
                  requestParameters,
                  opLocalId,
                  userSelectedClaimedId,
                  authenticatedAndApproved.booleanValue(),
                  false); // Sign after we added extensions.

          if (response instanceof DirectError) {
            directResponse(resp, response.keyValueFormEncoding());
            return;
          } else if (response instanceof AuthFailure) {
            redirectToAuthorisationPage(req, resp, requestParameters, serverBean);
            return;
          } else {
            String[] extensionsToSign = prepareResponse(serverBean, response, iwc, user, authReq);
            boolean signExtensions =
                iwma.getSettings().getBoolean(OpenIDConstants.PROPERTY_SIGN_EXTENSIONS, false);

            AuthSuccess success = (AuthSuccess) response;
            if (signExtensions) {
              success.setSignExtensions(extensionsToSign);
            }

            // Sign the auth success message.
            // This is required as AuthSuccess.buildSignedList has a `todo' tag now.
            manager.sign(success);

            // caller will need to decide which of the following to use:

            // option1: GET HTTP-redirect to the return_to URL
            //		                cleanUpBeforeReturning(iwc, loginExpireHandle);
            // Clean up before returning
            serverBean.invalidate();

            getDAO().createLogEntry(user.getUniqueId(), realm, "");

            resp.sendRedirect(response.getDestinationUrl(true));
            return;

            // option2: HTML FORM Redirection
            // RequestDispatcher dispatcher =
            // getServletContext().getRequestDispatcher("formredirection.jsp");
            // httpReq.setAttribute("parameterMap", response.getParameterMap());
            // httpReq.setAttribute("destinationUrl", response.getDestinationUrl(false));
            // dispatcher.forward(request, response);
            // return null;
          }
        } else {
          redirectToLoginPage(req, resp, requestParameters, serverBean, manager);
          return;
        }
      } else if (OpenIDConstants.PARAMETER_CHECK_AUTHENTICATION.equals(mode)) {
        // --- processing a verification request ---
        response = manager.verify(requestParameters);
        responseText = response.keyValueFormEncoding();
      } else {
        // --- error response ---
        response = DirectError.createDirectError("Unknown request");
        responseText = response.keyValueFormEncoding();
        serverBean.invalidate();
      }
    } catch (MessageException me) {
      me.printStackTrace();
      responseText = me.getMessage();
      serverBean.invalidate();
    } catch (AssociationException ae) {
      ae.printStackTrace();
      responseText = ae.getMessage();
      serverBean.invalidate();
    } catch (ServerException se) {
      se.printStackTrace();
      responseText = se.getMessage();
      serverBean.invalidate();
    }

    // return the result to the user
    directResponse(resp, responseText);
  }
  private Representation handle(ParameterList request) {
    Logger log = getLogger();
    log.info("Handle on OP");
    ConcurrentMap<String, Object> attribs = getContext().getAttributes();
    ServerManager manager = (ServerManager) attribs.get("openid_manager");
    log.info("OP endpoint = " + manager.getOPEndpointUrl());

    String mode =
        request.hasParameter("openid.mode") ? request.getParameterValue("openid.mode") : null;

    Message response;
    String responseText;

    if ("associate".equals(mode)) {
      // --- process an association request ---
      response = manager.associationResponse(request);
      responseText = response.keyValueFormEncoding();
    } else if ("checkid_setup".equals(mode) || "checkid_immediate".equals(mode)) {
      // interact with the user and obtain data needed to continue
      List<?> userData = userInteraction(request, manager.getOPEndpointUrl());

      String userSelectedId = (String) userData.get(0);
      String userSelectedClaimedId = (String) userData.get(1);
      Boolean authenticatedAndApproved = (Boolean) userData.get(2);

      // --- process an authentication request ---
      response =
          manager.authResponse(
              request,
              userSelectedId,
              userSelectedClaimedId,
              authenticatedAndApproved.booleanValue());

      if (response instanceof DirectError) {
        Form f = new Form();
        @SuppressWarnings("unchecked")
        Map<String, String> m = (Map<String, String>) response.getParameterMap();
        for (String key : m.keySet()) {
          f.add(key, m.get(key));
        }
        return f.getWebRepresentation();
      } else {
        // caller will need to decide which of the following to use:

        // option1: GET HTTP-redirect to the return_to URL
        // return new
        // StringRepresentation(response.getDestinationUrl(true));
        redirectSeeOther(response.getDestinationUrl(true));
        return new EmptyRepresentation();

        // option2: HTML FORM Redirection
        // RequestDispatcher dispatcher =
        // getServletContext().getRequestDispatcher("formredirection.jsp");
        // httpReq.setAttribute("prameterMap",
        // response.getParameterMap());
        // httpReq.setAttribute("destinationUrl",
        // response.getDestinationUrl(false));
        // dispatcher.forward(request, response);
        // return null;
      }
    } else if ("check_authentication".equals(mode)) {
      // --- processing a verification request ---
      response = manager.verify(request);
      log.info("OpenID : " + response.keyValueFormEncoding());
      responseText = response.keyValueFormEncoding();
    } else if (Method.GET.equals(getMethod())) {
      // Could be a discovery request
      sendXRDSLocation();
      return new StringRepresentation("XRDS Discovery Information");
    } else {
      // --- error response ---
      response = DirectError.createDirectError("Unknown request");
      responseText = response.keyValueFormEncoding();
    }

    // return the result to the user
    return new StringRepresentation(responseText);
  }