Example usage for org.springframework.validation BindingResult addError

List of usage examples for org.springframework.validation BindingResult addError

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult addError.

Prototype

void addError(ObjectError error);

Source Link

Document

Add a custom ObjectError or FieldError to the errors list.

Usage

From source file:com.test.springmvc.springmvcproject.IndexController.java

@RequestMapping(value = "register", method = RequestMethod.POST)
public String register(HttpSession session, ModelMap model, @Valid RegisterBean bean, BindingResult result) {

    if (!result.hasErrors()) {
        System.out.println("Pas d'erreurs !!");
        session.setAttribute("email_utilisateur", bean.getEmail());
        try {/*from   ww  w.  j  av  a2s.c om*/
            utilisateurService.create(bean);
        } catch (DuplicatedEntryException e) {
            result.addError(new FieldError("RegisterBean", "email", e.getMessage()));
            return "register";
        }
    } else {
        System.out.println("erreur presentes dans la validation : " + result.toString());
        return "register";
    }

    return "redirect:/index.do";
}

From source file:org.jblogcms.core.account.controller.ChangePasswordController.java

private boolean changePassword(ChangePasswordDTO changePasswordDTO, BindingResult result) {

    if (!Objects.equals(changePasswordDTO.getPassword(), changePasswordDTO.getPasswordVerification())) {

        String errorCode = messageSource.getMessage("fieldError.passwordsNotEqual", null, null);
        FieldError error = new FieldError("changePasswordDTO", "passwordVerification", errorCode);
        result.addError(error);
        return false;
    }/*from w  ww.ja  va2  s  . c  o m*/

    try {
        accountService.changePassword(changePasswordDTO);
    } catch (OldPasswordNotMatchedException e) {
        String errorCode = messageSource.getMessage("exception.oldPasswordNotMatched", null, null);
        FieldError error = new FieldError("changePasswordDTO", "oldPassword", errorCode);
        result.addError(error);
        return false;
    }
    return true;
}

From source file:com.company.simple.util.validator.GlobeValidator.java

protected void processConstraintViolations(Set<ConstraintViolation<Object>> violations, Errors errors) {
    for (ConstraintViolation<Object> violation : violations) {
        String field = violation.getPropertyPath().toString();
        FieldError fieldError = errors.getFieldError(field);
        if (fieldError == null || !fieldError.isBindingFailure()) {
            try {
                ConstraintDescriptor<?> cd = violation.getConstraintDescriptor();
                String errorCode = cd.getAnnotation().annotationType().getSimpleName();
                Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field, cd);
                if (errors instanceof BindingResult) {
                    // Can do custom FieldError registration with invalid value from ConstraintViolation,
                    // as necessary for Hibernate Validator compatibility (non-indexed set path in field)
                    BindingResult bindingResult = (BindingResult) errors;
                    String nestedField = bindingResult.getNestedPath() + field;
                    if ("".equals(nestedField)) {
                        String[] errorCodes = bindingResult.resolveMessageCodes(errorCode);
                        bindingResult.addError(new ObjectError(errors.getObjectName(), errorCodes, errorArgs,
                                violation.getMessage()));
                    } else {
                        Object invalidValue = violation.getInvalidValue();
                        if (!"".equals(field) && (invalidValue == violation.getLeafBean()
                                || (field.contains(".") && !field.contains("[]")))) {
                            // Possibly a bean constraint with property path: retrieve the actual property value.
                            // However, explicitly avoid this for "address[]" style paths that we can't handle.
                            invalidValue = bindingResult.getRawFieldValue(field);
                        }//from   w  w  w  .jav a 2 s .  co  m
                        String[] errorCodes = bindingResult.resolveMessageCodes(errorCode, field);
                        bindingResult.addError(new FieldError(errors.getObjectName(), nestedField, invalidValue,
                                false, errorCodes, errorArgs, violation.getMessage()));
                    }
                } else {
                    // got no BindingResult - can only do standard rejectValue call
                    // with automatic extraction of the current field value
                    errors.rejectValue(field, errorCode, errorArgs, violation.getMessage());
                }
            } catch (NotReadablePropertyException ex) {
                throw new IllegalStateException("JSR-303 validated property '" + field
                        + "' does not have a corresponding accessor for Spring data binding - "
                        + "check your DataBinder's configuration (bean property versus direct field access)",
                        ex);
            }
        }
    }
}

From source file:org.kew.rmf.matchconf.web.CustomWireController.java

@RequestMapping(value = "/{configType}_configs/{configName}/wires", method = RequestMethod.POST, produces = "text/html")
public String create(@PathVariable("configType") String configType,
        @PathVariable("configName") String configName, @Valid Wire wire, BindingResult bindingResult,
        Model uiModel, HttpServletRequest httpServletRequest) {
    // assert unique_together:config&name
    if (Configuration.findConfigurationsByNameEquals(configName).getSingleResult()
            .getWireForName(wire.getName()) != null) {
        bindingResult.addError(new ObjectError("wire.name",
                "There is already a Wire set up for this configuration with this name."));
    }/*from www  .  j  a  va 2 s.com*/
    this.customValidation(configName, wire, bindingResult);
    if (bindingResult.hasErrors()) {
        populateEditForm(uiModel, configName, wire);
        return String.format("%s_config_wires/create", configType);
    }
    uiModel.asMap().clear();
    Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult();
    wire.setConfiguration(config);
    wire.persist();
    config.getWiring().add(wire);
    config.merge();
    return String.format("redirect:/%s_configs/", configType)
            + encodeUrlPathSegment(configName, httpServletRequest) + "/wires/"
            + encodeUrlPathSegment(wire.getName(), httpServletRequest);
}

From source file:com.stormpath.tooter.controller.PasswordController.java

@RequestMapping(value = "/password/forgot", method = RequestMethod.POST)
public String processResetPassword(User customer, BindingResult result) {

    resetPasswordValidator.validate(customer, result);

    if (result.hasErrors()) {
        return "resetPassword";
    } else {//from   w w w.  ja v  a 2 s .com
        try {
            stormpath.getApplication().sendPasswordResetEmail(customer.getEmail());
        } catch (ResourceException re) {
            result.addError(new ObjectError("email",
                    re.getCode() == 404 ? "The provided email for password reset does not exist."
                            : re.getMessage()));
            re.printStackTrace();
            return "resetPassword";
        }

        //form success
        return "resetPasswordMsg";
    }
}

From source file:org.kew.rmf.matchconf.web.CustomTransformerController.java

@RequestMapping(value = "/{configType}_configs/{configName}/transformers", method = RequestMethod.POST, produces = "text/html")
public String create(@PathVariable("configType") String configType,
        @PathVariable("configName") String configName, @Valid Transformer transformer,
        BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
    // assert unique_together:config&name
    if (Configuration.findConfigurationsByNameEquals(configName).getSingleResult()
            .getTransformerForName(transformer.getName()) != null) {
        bindingResult.addError(new ObjectError("transformer.name",
                "There is already a Transformer set up for this configuration with this name."));
    }/*from w w  w .j a  v  a 2s.  c  om*/
    this.customValidation(configName, transformer, bindingResult);
    if (bindingResult.hasErrors()) {
        populateEditForm(uiModel, configType, configName, transformer);
        return "config_transformers/create";
    }
    uiModel.asMap().clear();
    Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult();
    transformer.setConfiguration(config);
    transformer.persist();
    config.getTransformers().add(transformer);
    config.merge();
    return "redirect:/{configType}_configs/" + encodeUrlPathSegment(configName, httpServletRequest)
            + "/transformers/" + encodeUrlPathSegment(transformer.getName(), httpServletRequest);
}

From source file:org.kew.rmf.matchconf.web.CustomReporterController.java

@RequestMapping(value = "/{configType}_configs/{configName}/reporters", method = RequestMethod.POST, produces = "text/html")
public String create(@PathVariable("configType") String configType,
        @PathVariable("configName") String configName, @Valid Reporter reporter, BindingResult bindingResult,
        Model uiModel, HttpServletRequest httpServletRequest) {
    // assert unique_together:config&name
    if (Configuration.findConfigurationsByNameEquals(configName).getSingleResult()
            .getReporterForName(reporter.getName()) != null) {
        bindingResult.addError(new ObjectError("reporter.name",
                "There is already a LuceneReporter set up for this configuration with this name."));
    }// w w  w.ja  v a2  s  .  c om
    this.customValidation(configName, reporter, bindingResult);
    if (bindingResult.hasErrors()) {
        populateEditForm(uiModel, configType, configName, reporter);
        return "config_reporters/create";
    }
    uiModel.asMap().clear();
    Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult();
    reporter.setConfig(config);
    reporter.persist();
    config.getReporters().add(reporter);
    config.merge();
    return String.format("redirect:/%s_configs/", configType)
            + encodeUrlPathSegment(configName, httpServletRequest) + "/reporters/"
            + encodeUrlPathSegment(reporter.getName(), httpServletRequest);
}

From source file:org.axonframework.examples.addressbook.web.ContactsController.java

/**
 * Checks if the entered data for a contact is valid and if the provided contact has not yet been taken.
 *
 * @param contact       Contact to validate
 * @param bindingResult BindingResult that can contain error and can be used to store additional errors
 * @return true if the contact has errors, false otherwise
 *///from   w w w .j  av a2 s  .c o  m
private boolean contactHasErrors(ContactEntry contact, BindingResult bindingResult) {
    if (bindingResult.hasErrors() || !contactNameRepository.vacantContactName(contact.getName())) {
        ObjectError error = new FieldError("contact", "name",
                "The provided name \'" + contact.getName() + "\' already exists");
        bindingResult.addError(error);
        return true;
    }
    return false;
}

From source file:org.kew.rmf.matchconf.web.CustomMatcherController.java

@RequestMapping(value = "/{configType}_configs/{configName}/matchers", method = RequestMethod.POST, produces = "text/html")
public String create(@PathVariable("configType") String configType,
        @PathVariable("configName") String configName, @Valid Matcher matcher, BindingResult bindingResult,
        Model uiModel, HttpServletRequest httpServletRequest) {
    Configuration config = Configuration.findConfigurationsByNameEquals(configName).getSingleResult();
    // assert unique_together:config&name
    if (config.getMatcherForName(matcher.getName()) != null) {
        bindingResult.addError(new ObjectError("matcher.name",
                "There is already a Matcher set up for this configuration with this name."));
    }/*from   ww w. j  av a  2s  .  com*/
    this.customValidation(configName, matcher, bindingResult);
    if (bindingResult.hasErrors()) {
        populateEditForm(uiModel, configType, configName, matcher);
        return "config_matchers/create";
    }
    uiModel.asMap().clear();
    matcher.setConfiguration(config);
    matcher.persist();
    config.getMatchers().add(matcher);
    config.merge();
    return "redirect:/{configType}_configs/" + encodeUrlPathSegment(configName, httpServletRequest)
            + "/matchers/" + encodeUrlPathSegment(matcher.getName(), httpServletRequest);
}

From source file:org.jblogcms.core.account.controller.AddAccountController.java

private Account createAccount(NewAccountDTO newAccountDTO, BindingResult result) {

    Account account = null;//from w w  w .  jav  a2s . c o  m

    if (!Objects.equals(newAccountDTO.getPassword(), newAccountDTO.getPasswordVerification())) {

        String errorCode = messageSource.getMessage("fieldError.passwordsNotEqual", null, null);
        FieldError error = new FieldError("user", "passwordVerification", errorCode);
        result.addError(error);
        return null;
    }

    if (Objects.equals(newAccountDTO.getRole(), "admin")
            && accountService.countAllAccountsWithRoleAdmin() > 0) {

        String errorCode = messageSource.getMessage("fieldError.adminAccountExistsAlready", null, null);
        FieldError error = new FieldError("user", "*", errorCode);
        result.addError(error);
        return null;
    }

    try {
        account = accountService.addAccount(newAccountDTO);
    } catch (DuplicateEmailException e) {
        String errorCode = messageSource.getMessage(e.getLocalMessage(), null, null);

        FieldError error = new FieldError("user", "email", newAccountDTO.getEmail(), false,
                new String[] { errorCode }, new Object[] {}, errorCode);
        result.addError(error);
    }
    return account;
}