예제 #1
0
  public static ActionForm setFormByQueryParam(ActionForm form, String queryParamName) {
    try {
      String paramSeparator = "~`~";
      String paramValueSeparator = "=`=";
      Class clazz = Class.forName(form.getClass().getName());
      Method method =
          clazz.getDeclaredMethod(
              "get" + queryParamName.substring(0, 1).toUpperCase() + queryParamName.substring(1),
              (Class[]) null);
      String allQueryParam = StringUtil.nullToEmptyOfObject(method.invoke(form, (Object[]) null));
      String[] allQueryParamArray = split(allQueryParam, paramSeparator);
      Method[] methods = clazz.getDeclaredMethods();
      // 针对当前form设值
      setClassProp(methods, allQueryParamArray, paramSeparator, paramValueSeparator, form);
      // 针对父form设值
      methods = clazz.getSuperclass().getDeclaredMethods();
      // form=form.getClass().getSuperclass().cast(form);
      setClassProp(methods, allQueryParamArray, paramSeparator, paramValueSeparator, form);

    } catch (Exception e) {
      System.out.println(e);
      System.out.println("error when setting values in Helper.setFormByQueryParam==" + e);
    }
    return form;
  }
예제 #2
0
  protected XWikiContext initializeXWikiContext(
      ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse resp)
      throws XWikiException, ServletException {
    String action = mapping.getName();

    XWikiRequest request = new XWikiServletRequest(req);
    XWikiResponse response = new XWikiServletResponse(resp);
    XWikiContext context =
        Utils.prepareContext(
            action, request, response, new XWikiServletContext(this.servlet.getServletContext()));

    // This code is already called by struts.
    // However struts will also set all the parameters of the form data
    // directly from the request objects.
    // However because of bug http://jira.xwiki.org/jira/browse/XWIKI-2422
    // We need to perform encoding of windows-1252 chars in ISO mode
    // So we need to make sure this code is called
    // TODO: completely get rid of struts so that we control this part of the code and can reduce
    // drastically the
    // number of calls
    if (form != null) {
      form.reset(mapping, request);
    }

    // Add the form to the context
    context.setForm((XWikiForm) form);

    // Initialize the Container component which is the new way of transporting the Context in the
    // new
    // component architecture.
    initializeContainerComponent(context);

    return context;
  }
예제 #3
0
 public void reset(ActionMapping mapping, HttpServletRequest request) {
   try {
     request.setCharacterEncoding("UTF-8");
   } catch (UnsupportedEncodingException ex) {
     ex.printStackTrace();
   }
   super.reset(mapping, request);
 }
예제 #4
0
  /** Hooks into populate process to call form populate method if form is an instanceof PojoForm. */
  @Override
  protected void processPopulate(
      HttpServletRequest request,
      HttpServletResponse response,
      ActionForm form,
      ActionMapping mapping)
      throws ServletException {
    if (form instanceof KualiForm) {
      // Add the ActionForm to GlobalVariables
      // This will allow developers to retrieve both the Document and any
      // request parameters that are not
      // part of the Form and make them available in ValueFinder classes
      // and other places where they are needed.
      KNSGlobalVariables.setKualiForm((KualiForm) form);
    }

    // if not PojoForm, call struts populate
    if (!(form instanceof PojoForm)) {
      super.processPopulate(request, response, form, mapping);
      return;
    }

    final String previousRequestGuid =
        request.getParameter(
            KualiRequestProcessor.PREVIOUS_REQUEST_EDITABLE_PROPERTIES_GUID_PARAMETER_NAME);

    ((PojoForm) form).clearEditablePropertyInformation();
    ((PojoForm) form).registerStrutsActionMappingScope(mapping.getScope());

    String multipart = mapping.getMultipartClass();
    if (multipart != null) {
      request.setAttribute(Globals.MULTIPART_KEY, multipart);
    }

    form.setServlet(this.servlet);
    form.reset(mapping, request);

    ((PojoForm) form).setPopulateEditablePropertiesGuid(previousRequestGuid);
    // call populate on ActionForm
    ((PojoForm) form).populate(request);
    request.setAttribute("UnconvertedValues", ((PojoForm) form).getUnconvertedValues().keySet());
    request.setAttribute("UnconvertedHash", ((PojoForm) form).getUnconvertedValues());
  }
  public void reset(ActionMapping arg0, ServletRequest arg1) {
    // TODO Auto-generated method stub
    super.reset(arg0, arg1);

    this.idComando = "";

    this.descricaoComando = "";

    this.valorDebito = "";

    this.numeroCpf = "";

    this.numeroCnpj = "";

    this.idImovel = "";
  }
예제 #6
0
  /** 保存对象的Action函数. */
  public ActionForward save(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response) {
    if (isCancelled(request)) return list(mapping, form, request, response);
    if (!isTokenValid(request)) {
      saveDirectlyError(request, "重复提交");
      return mapping.findForward(LIST);
    }
    resetToken(request);

    // run validation rules on this form
    ActionMessages errors = form.validate(mapping, request);
    if (!errors.isEmpty()) {
      saveErrors(request, errors);
      refrenceData(request);
      return mapping.findForward(EDIT);
    }

    T object;
    // 如果是修改操作,id is not blank
    if (StringUtils.isNotBlank(request.getParameter(idName))) {
      object = doGetEntity(form, request);
      if (object == null) {
        saveError(request, "entity.missing");
        return mapping.findForward(LIST);
      }
    } else { // 否则为新增操作
      object = doNewEntity(form, request);
    }
    try {
      // 将lazyform内容绑定到object
      initEntity(form, request, object);
      doSaveEntity(form, request, object);
      savedMessage(request, object);
    } catch (BusinessException e) {
      log.error(e.getMessage(), e);
      saveDirectlyError(request, e.getMessage());
      refrenceData(request);
      return mapping.findForward(EDIT);
    }
    return mapping.findForward(SUCCESS);
  }
예제 #7
0
  public static ActionForm setQueryParam(ActionForm form, String queryParamName) {
    try {
      StringBuffer sbf = new StringBuffer(100);
      String paramSeparator = "~`~";
      String paramValueSeparator = "=`=";
      Class clazz = Class.forName(form.getClass().getName());
      Method method =
          clazz.getDeclaredMethod(
              "get" + queryParamName.substring(0, 1).toUpperCase() + queryParamName.substring(1),
              (Class[]) null);
      Method[] methods = clazz.getDeclaredMethods();
      String allQueryParamName =
          StringUtil.nullToEmptyOfObject(method.invoke(form, (Object[]) null));
      allQueryParamName = paramSeparator + allQueryParamName + paramSeparator;
      // 针对当前form取值
      sbf =
          getAllClassProp(
              methods, allQueryParamName, paramSeparator, paramValueSeparator, form, sbf);
      // 针对父form取值
      methods = clazz.getSuperclass().getDeclaredMethods();
      sbf =
          getAllClassProp(
              methods, allQueryParamName, paramSeparator, paramValueSeparator, form, sbf);

      if (sbf != null && !"".equals(sbf.toString().trim())) {
        method =
            clazz.getDeclaredMethod(
                "set" + queryParamName.substring(0, 1).toUpperCase() + queryParamName.substring(1),
                String.class);
        method.invoke(form, sbf.toString());
      }
    } catch (Exception e) {
      System.out.println("error when setting values in Helper.setQueryParam==" + e);
    }
    return form;
  }
예제 #8
0
 public void reset(ActionMapping map, HttpServletRequest req) {
   super.reset(map, req);
 }
예제 #9
0
  @Override
  public void process(final HttpServletRequest request, final HttpServletResponse response)
      throws IOException, ServletException {
    // indicates that we are running in legacy KNS context
    LegacyUtils.beginLegacyContext();
    try {
      if (LOG.isInfoEnabled()) {
        LOG.info(
            new StringBuffer("Started processing request: '")
                .append(request.getRequestURI())
                .append("' w/ query string: '")
                .append(request.getQueryString())
                .append("'"));
      }

      try {
        strutsProcess(request, response);
      } catch (FileUploadLimitExceededException e) {
        ActionForward actionForward =
            processException(request, response, e, e.getActionForm(), e.getActionMapping());
        processForwardConfig(request, response, actionForward);
      } finally {
        KNSGlobalVariables.setKualiForm(null);
      }

      try {
        ActionForm form = WebUtils.getKualiForm(request);

        if (form != null && form instanceof KualiDocumentFormBase) {
          String docId = ((KualiDocumentFormBase) form).getDocId();
          if (docId != null) {
            MDC.put(MDC_DOC_ID, docId);
          }
        }

        String refreshCaller = request.getParameter(KRADConstants.REFRESH_CALLER);
        if (form != null
            && KualiDocumentFormBase.class.isAssignableFrom(form.getClass())
            && !KRADConstants.QUESTION_REFRESH.equalsIgnoreCase(refreshCaller)) {
          KualiDocumentFormBase docForm = (KualiDocumentFormBase) form;
          Document document = docForm.getDocument();
          String docFormKey = docForm.getFormKey();

          UserSession userSession =
              (UserSession) request.getSession().getAttribute(KRADConstants.USER_SESSION_KEY);

          if (WebUtils.isDocumentSession(document, docForm)) {
            getSessionDocumentService()
                .setDocumentForm(docForm, userSession, request.getRemoteAddr());
          }

          Boolean exitingDocument = (Boolean) request.getAttribute(KRADConstants.EXITING_DOCUMENT);

          if (exitingDocument != null && exitingDocument.booleanValue()) {
            // remove KualiDocumentFormBase object from session and
            // table.
            getSessionDocumentService()
                .purgeDocumentForm(
                    docForm.getDocument().getDocumentNumber(),
                    docFormKey,
                    userSession,
                    request.getRemoteAddr());
          }
        }

        if (LOG.isInfoEnabled()) {
          LOG.info(
              new StringBuffer("Finished processing request: '")
                  .append(request.getRequestURI())
                  .append("' w/ query string: '")
                  .append(request.getQueryString())
                  .append("'"));
        }

      } finally {
        // MDC docId key is set above, and also during super.process() in the call to
        // processActionForm
        MDC.remove(MDC_DOC_ID);
      }
    } finally {
      LegacyUtils.endLegacyContext();
    }
  }
예제 #10
0
  /**
   * Hooks into validate to catch any errors from the populate, and translate the ErrorMap to
   * ActionMessages.
   */
  @Override
  protected boolean processValidate(
      HttpServletRequest request,
      HttpServletResponse response,
      ActionForm form,
      ActionMapping mapping)
      throws IOException, ServletException, InvalidCancelException {

    // skip form validate if we had errors from populate
    if (GlobalVariables.getMessageMap().hasNoErrors()) {
      if (form == null) {
        return (true);
      }
      // Was this request cancelled?
      if (request.getAttribute(Globals.CANCEL_KEY) != null) {
        if (LOG.isDebugEnabled()) {
          LOG.debug(" Cancelled transaction, skipping validation");
        }
        return (true);
      }

      // Has validation been turned off for this mapping?
      if (!mapping.getValidate()) {
        return (true);
      }

      // call super to call forms validate
      super.processValidate(request, response, form, mapping);
    }

    publishMessages(request);
    if (!GlobalVariables.getMessageMap().hasNoErrors()) {
      // Special handling for multipart request
      if (form.getMultipartRequestHandler() != null) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("  Rolling back multipart request");
        }
        form.getMultipartRequestHandler().rollback();
      }

      // Fix state that could be incorrect because of validation failure
      if (form instanceof PojoForm) {
        ((PojoForm) form).processValidationFail();
      }

      // Was an input path (or forward) specified for this mapping?
      String input = mapping.getInput();
      if (input == null) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("  Validation failed but no input form available");
        }
        response.sendError(
            HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
            getInternal().getMessage("noInput", mapping.getPath()));
        return (false);
      }

      if (moduleConfig.getControllerConfig().getInputForward()) {
        ForwardConfig forward = mapping.findForward(input);
        processForwardConfig(request, response, forward);
      } else {
        internalModuleRelativeForward(input, request, response);
      }

      return (false);
    }
    return true;
  }
예제 #11
0
 @Override
 public void reset(ActionMapping mapping, HttpServletRequest request) {
   super.reset(mapping, request);
   username = null;
   password = null;
 }
예제 #12
0
 /**
  * Reset form bean.
  *
  * @param mapping the action mapping associated with this form bean
  * @param request the current http servlet request
  */
 @Override
 public void reset(ActionMapping mapping, HttpServletRequest request) {
   super.reset(mapping, request);
   reset();
 }
예제 #13
0
  /**
   * Guarda el documento electrónico.
   *
   * @param mapping {@link ActionMapping} con los mapeos asociado.
   * @param form {@link ActionForm} asociado al action.
   * @param request {@link HttpServletRequest}
   * @param response {@link HttpServletResponse}
   */
  protected void saveExecuteLogic(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    try {
      logger.info("Inicio de saveExecuteLogic");

      // Validar el formulario
      ActionErrors errores = form.validate(mapping, request);
      if ((errores == null) || errores.isEmpty()) {
        logger.info("Formulario validado");

        // Recoger la información del documento
        DocDocumentoExtVO documento = new DocDocumentoExtVO();
        ((DocumentoForm) form).populate(documento);
        if (logger.isDebugEnabled()) logger.debug("DocDocumentoVO:\n" + documento.toString());

        DocTCapturaVO tarea =
            (DocTCapturaVO) getFromTemporalSession(request, DocumentosConstants.TAREA_KEY);
        if (StringUtils.isBlank(documento.getId())) {
          if (tarea != null) {
            // Crear el documento
            ((DocumentoForm) form)
                .set(
                    getGestionDocumentosElectronicosBI(request)
                        .insertDocumentoDesdeTarea(documento));
          } else {
            // Crear el documento
            ((DocumentoForm) form)
                .set(
                    getGestionDocumentosElectronicosBI(request)
                        .insertDocumentoDesdeCuadro(documento));
          }

          // Eliminar la invocación anterior
          popLastInvocation(request);
        } else {
          if (tarea != null) {
            // Modificar el documento
            ((DocumentoForm) form)
                .set(
                    getGestionDocumentosElectronicosBI(request)
                        .updateDocumentoDesdeTarea(documento));
          } else {
            // Modificar el documento
            ((DocumentoForm) form)
                .set(
                    getGestionDocumentosElectronicosBI(request)
                        .updateDocumentoDesdeCuadro(documento));
          }
        }

        RelacionEntregaVO relacion =
            (RelacionEntregaVO)
                getFromTemporalSession(request, TransferenciasConstants.RELACION_KEY);
        if (relacion != null) {
          ServiceRepository services =
              ServiceRepository.getInstance(ServiceClient.create(getAppUser(request)));
          GestionRelacionesEntregaBI relacionBI = services.lookupGestionRelacionesBI();
          if (relacion.isRechazada()) {
            relacion.setEstado(EstadoREntrega.ABIERTA.getIdentificador());
            try {
              relacionBI.updateRelacion(relacion);
            } catch (ActionNotAllowedException e) {
              guardarError(request, e);
            }
          }
        }

        // Actualizar el árbol de documentos
        request.setAttribute(DocumentosConstants.REFRESH_VIEW_KEY, Boolean.TRUE);

        setReturnActionFordward(
            request,
            redirectForwardMethod(
                request,
                "/documento",
                "method",
                "retrieve"
                    + (documento.getId() != null ? "&id=" + documento.getId() : "")
                    + (documento.getIdObjeto() != null
                        ? "&idObjeto=" + documento.getIdObjeto()
                        : "")
                    + "&tipoObjeto="
                    + documento.getTipoObjeto()));
      } else {
        logger.info("Formulario inv\u00E1lido");

        // Añadir los errores al request
        obtenerErrores(request, true).add(errores);

        setReturnActionFordward(request, mapping.findForward("editar_documento"));
      }
    } catch (Exception e) {
      logger.error("Error al guardar el documento", e);
      obtenerErrores(request, true)
          .add(ActionErrors.GLOBAL_ERROR, new ActionError(Constants.ERROR_ALMACENAR_DOCUMENTO));

      setReturnActionFordward(request, mapping.findForward("editar_documento"));
    }
  }
  /**
   * Create an appropriate form bean in the appropriate scope, if one does not already exist.
   *
   * @param context FacesContext for the current request
   * @exception IllegalArgumentException if no ActionConfig for the specified action attribute can
   *     be located
   * @exception IllegalArgumentException if no FormBeanConfig for the specified form bean can be
   *     located
   * @exception IllegalArgumentException if no ModuleConfig can be located for this application
   *     module
   */
  public void createActionForm(FacesContext context) {

    // Look up the application module configuration information we need
    ModuleConfig moduleConfig = lookupModuleConfig(context);

    // Look up the ActionConfig we are processing
    String action = getAction();
    ActionConfig actionConfig = moduleConfig.findActionConfig(action);
    if (actionConfig == null) {
      throw new IllegalArgumentException("Cannot find action '" + action + "' configuration");
    }

    // Does this ActionConfig specify a form bean?
    String name = actionConfig.getName();
    if (name == null) {
      return;
    }

    // Look up the FormBeanConfig we are processing
    FormBeanConfig fbConfig = moduleConfig.findFormBeanConfig(name);
    if (fbConfig == null) {
      throw new IllegalArgumentException("Cannot find form bean '" + name + "' configuration");
    }

    // Does a usable form bean attribute already exist?
    String attribute = actionConfig.getAttribute();
    String scope = actionConfig.getScope();
    ActionForm instance = null;
    if ("request".equals(scope)) {
      instance = (ActionForm) context.getExternalContext().getRequestMap().get(attribute);
    } else if ("session".equals(scope)) {
      HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
      instance = (ActionForm) context.getExternalContext().getSessionMap().get(attribute);
    }
    if (instance != null) {
      if (fbConfig.getDynamic()) {
        String className = ((DynaBean) instance).getDynaClass().getName();
        if (className.equals(fbConfig.getName())) {
          if (log.isDebugEnabled()) {
            log.debug(
                " Recycling existing DynaActionForm instance " + "of type '" + className + "'");
          }
          return;
        }
      } else {
        try {
          Class configClass = RequestUtils.applicationClass(fbConfig.getType());
          if (configClass.isAssignableFrom(instance.getClass())) {
            if (log.isDebugEnabled()) {
              log.debug(
                  " Recycling existing ActionForm instance "
                      + "of class '"
                      + instance.getClass().getName()
                      + "'");
            }
            return;
          }
        } catch (Throwable t) {
          throw new IllegalArgumentException(
              "Cannot load form bean class '" + fbConfig.getType() + "'");
        }
      }
    }

    // Create a new form bean instance
    if (fbConfig.getDynamic()) {
      try {
        DynaActionFormClass dynaClass = DynaActionFormClass.createDynaActionFormClass(fbConfig);
        instance = (ActionForm) dynaClass.newInstance();
        if (log.isDebugEnabled()) {
          log.debug(
              " Creating new DynaActionForm instance " + "of type '" + fbConfig.getType() + "'");
          log.trace(" --> " + instance);
        }
      } catch (Throwable t) {
        throw new IllegalArgumentException(
            "Cannot create form bean of type '" + fbConfig.getType() + "'");
      }
    } else {
      try {
        instance = (ActionForm) RequestUtils.applicationInstance(fbConfig.getType());
        if (log.isDebugEnabled()) {
          log.debug(" Creating new ActionForm instance " + "of type '" + fbConfig.getType() + "'");
          log.trace(" --> " + instance);
        }
      } catch (Throwable t) {
        throw new IllegalArgumentException(
            "Cannot create form bean of class '" + fbConfig.getType() + "'");
      }
    }

    // Configure and cache the form bean instance in the correct scope
    ActionServlet servlet =
        (ActionServlet)
            context.getExternalContext().getApplicationMap().get(Globals.ACTION_SERVLET_KEY);
    instance.setServlet(servlet);
    if ("request".equals(scope)) {
      context.getExternalContext().getRequestMap().put(attribute, instance);
    } else if ("session".equals(scope)) {
      context.getExternalContext().getSessionMap().put(attribute, instance);
    }
  }
예제 #15
0
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    ActionMessages msgs = new ActionMessages();

    SessionInfo sessionInfo = LogonControllerFactory.getInstance().getSessionInfo(request);

    if (sessionInfo == null
        && request.getSession().getAttribute(Constants.SESSION_LOCKED) == null
        && LogonControllerFactory.getInstance().hasClientLoggedOn(request, response)
            == LogonController.LOGGED_ON) {
      if (log.isDebugEnabled()) log.debug(request.getRemoteHost() + " is already authenticated");

      return mapping.findForward("success");
    }

    /*
     * Get the authentication session and module to use to validate this
     * authentication attempt
     */
    AuthenticationScheme scheme =
        (AuthenticationScheme) request.getSession().getAttribute(Constants.AUTH_SESSION);
    LogonStateAndCache logonStateMachine =
        (LogonStateAndCache)
            request.getSession().getAttribute(LogonStateAndCache.LOGON_STATE_MACHINE);

    // there are different users so we need to logon again, clearing the authentication scheme and
    // logon machine.
    if (sessionInfo != null
        && logonStateMachine != null
        && !sessionInfo.getUser().equals(logonStateMachine.getUser())) {
      request.getSession().removeAttribute(Constants.AUTH_SESSION);
      request.getSession().removeAttribute(LogonStateAndCache.LOGON_STATE_MACHINE);
      LogonControllerFactory.getInstance().logoffSession(request, response);
      msgs.add(
          Globals.ERROR_KEY,
          new ActionMessage("login.logonNotAllowed", "Session no longer valid, logon again."));
      saveErrors(request, msgs);
      return new RedirectWithMessages(mapping.findForward("logon"), request);
    }

    if (logonStateMachine == null) {
      logonStateMachine =
          new LogonStateAndCache(LogonStateAndCache.STATE_STARTED, request.getSession());
      request.getSession().setAttribute(LogonStateAndCache.LOGON_STATE_MACHINE, logonStateMachine);
    }
    if (scheme == null) {

      ActionForward fwd = null;
      try {
        fwd =
            ShowLogonAction.checkAuthSession(
                null, false, mapping, request, response, logonStateMachine);
      } catch (CoreException ce) {

      } catch (Throwable e) {
        log.error("Logon not allowed.", e);
        ActionMessages errs = new ActionMessages();
        if (e instanceof CoreException) {
          errs.add(Globals.ERROR_KEY, ((CoreException) e).getBundleActionMessage());
        } else {
          errs.add(
              Globals.ERROR_KEY,
              new ActionMessage("login.logonNotAllowed", "Please contact your administrator."));
        }
        saveErrors(request, errs);
        request.getSession().removeAttribute(Constants.AUTH_SESSION);
        request.getSession().removeAttribute(LogonStateAndCache.LOGON_STATE_MACHINE);
        if (form != null) form.reset(mapping, request);
        return new RedirectWithMessages(mapping.findForward("failed"), request);
      }
      if (fwd != null) {
        scheme = (AuthenticationScheme) request.getSession().getAttribute(Constants.AUTH_SESSION);
      }
    }

    if (scheme != null) {
      AuthenticationModule module = scheme.currentAuthenticationModule();
      if (module == null) {
        log.error("No authentication module.");
        request.getSession().removeAttribute(Constants.AUTH_SESSION);
        return mapping.findForward("logon");
      }

      try {
        // If there is no user in the scheme then it is an invalid login
        if (scheme.getUser() == null) {
          throw new InvalidLoginCredentialsException();
        }

        // Check the account is enabled and not locked
        if (!PolicyUtil.isEnabled(scheme.getUser())) {
          throw new AccountLockedException(scheme.getUsername(), "Account disabled.", true, 0);
        }

        // Check for locks
        LogonControllerFactory.getInstance()
            .checkForAccountLock(
                scheme.getUsername(), scheme.getUser().getRealm().getResourceName());

        // Authenticate
        authenticate(scheme, request);

        // Check logon is currently allowed
        String logonNotAllowedReason =
            LogonControllerFactory.getInstance().checkLogonAllowed(scheme.getUser());

        if (logonNotAllowedReason != null) {
          log.warn("Logon not allowed because '" + logonNotAllowedReason + "'");
          msgs.add(
              Globals.ERROR_KEY, new ActionMessage("login.logonNotAllowed", logonNotAllowedReason));
          saveErrors(request, msgs);
          return new RedirectWithMessages(mapping.findForward("logon"), request);
        }

        // Check for the next authentication modules
        AuthenticationModule nextModule = scheme.nextAuthenticationModule();
        if (nextModule != null
            && request.getSession().getAttribute(Constants.SESSION_LOCKED) == null) {
          if (log.isDebugEnabled())
            log.debug(
                "There are more authentication modules to satisfy (current mapping = "
                    + mapping.getPath());
          ActionForward fw = new RedirectWithMessages(mapping.findForward("logon"), request);
          return fw;
        }

        return finishAuthentication(scheme, request, response);
      } catch (InputRequiredException ex) {
        // The page wants to display or redirect somewhere
        if (ex.getForward() == null) return mapping.findForward("logon");
        else return ex.getForward();
      } catch (AccountLockedException ale) {
        return accountLocked(mapping, request, ale, msgs);
      } catch (InvalidLoginCredentialsException ex) {
        log.error("[" + request.getRemoteHost() + "] authentication failed", ex);

        LogonForm logonForm = (LogonForm) form;

        CoreServlet.getServlet()
            .fireCoreEvent(
                new CoreEvent(this, CoreEventConstants.LOGON, null, null, ex)
                    .addAttribute(
                        CoreAttributeConstants.EVENT_ATTR_IP_ADDRESS, request.getRemoteAddr())
                    .addAttribute(CoreAttributeConstants.EVENT_ATTR_HOST, request.getRemoteHost())
                    .addAttribute(CoreAttributeConstants.EVENT_ATTR_SCHEME, scheme.getSchemeName())
                    .addAttribute(
                        CoreAttributeConstants.EVENT_ATTR_ACCOUNT, logonForm.getUsername()));

        request.getSession().removeAttribute(LogonStateAndCache.LOGON_STATE_MACHINE);
        request.getSession().removeAttribute(Constants.AUTH_SESSION);

        try {
          scheme.setAccountLock(
              LogonControllerFactory.getInstance()
                  .logonFailed(
                      ((LogonForm) form).getUsername(),
                      ((LogonForm) form).getRealmName(),
                      scheme.getAccountLock()));
        } catch (AccountLockedException ale) {
          return accountLocked(mapping, request, ale, msgs);
        }

        msgs.add(Globals.ERROR_KEY, new ActionMessage("login.invalidCredentials"));
        saveErrors(request, msgs);
        return new RedirectWithMessages(mapping.findForward("logon"), request);
      } catch (Exception e) {
        log.error("Internal error authenticating.", e);
        msgs.add(
            Globals.ERROR_KEY, new BundleActionMessage("security", "login.error", e.getMessage()));
        saveErrors(request, msgs);
        request.getSession().setAttribute(Constants.EXCEPTION, e);
        request.getSession().removeAttribute(LogonStateAndCache.LOGON_STATE_MACHINE);
        request.getSession().removeAttribute(Constants.AUTH_SESSION);
        return new RedirectWithMessages(mapping.findForward("logon"), request);
      }
    } else {
      ActionMessages errs = new ActionMessages();
      errs.add(
          Globals.MESSAGE_KEY,
          new BundleActionMessage("security", "login.logonNotAllowed", "No scheme available."));
      saveErrors(request, errs);
      request.getSession().removeAttribute(LogonStateAndCache.LOGON_STATE_MACHINE);
      request.getSession().removeAttribute(Constants.AUTH_SESSION);
      if (form != null) form.reset(mapping, request);
      return new RedirectWithMessages(mapping.findForward("logon"), request);
    }
  }