Example usage for org.springframework.validation FieldError getDefaultMessage

List of usage examples for org.springframework.validation FieldError getDefaultMessage

Introduction

In this page you can find the example usage for org.springframework.validation FieldError getDefaultMessage.

Prototype

@Override
    @Nullable
    public String getDefaultMessage() 

Source Link

Usage

From source file:org.terasoluna.tourreservation.app.managecustomer.CustomerPassEqualsValidatorTest.java

/**
 * password check error//from  w  ww .j a  va  2  s.  co m
 */
@Test
public void testValidate02() {
    CustomerPassEqualsValidator validator = new CustomerPassEqualsValidator();
    CustomerForm customer = new CustomerForm();
    customer.setCustomerPass("12345");
    customer.setCustomerPassConfirm("1234");

    BindingResult result = new DirectFieldBindingResult(customer, "CustomerForm");

    // run
    validator.validate(customer, result);

    // assert
    assertThat(result.hasErrors(), is(true));

    FieldError error = result.getFieldError("customerPass");

    if (error != null) {
        assertThat(error.getCode(), is("NotEquals.customerPass"));
        assertThat(error.getDefaultMessage(), is("Password and password confirm is not same."));
    } else {
        fail("error");
    }

}

From source file:br.com.modoagil.asr.rest.support.RESTErrorHandler.java

/**
 * Manipula exceo de validao de objetos nos servios
 *
 * @param ex/* w  ww. j a  va  2  s .c  o m*/
 *            {@link MethodArgumentNotValidException}
 * @return resposta ao cliente
 */
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
public Response<E> processMethodArgumentNotValidException(final MethodArgumentNotValidException ex) {
    this.logger.info("handleMethodArgumentNotValidException - Catching: " + ex.getClass().getSimpleName(), ex);
    final BindingResult result = ex.getBindingResult();
    final FieldError fieldError = result.getFieldError();
    final String message = this.messageSource.getMessage(fieldError.getDefaultMessage(), null, null);
    return new ResponseBuilder<E>().success(false).status(HttpStatus.BAD_REQUEST).message(message).build();
}

From source file:com.google.ie.common.validation.ProjectValidator.java

@Override
public void validate(Object target, Errors errors) {
    ProjectDetail projectDetail = (ProjectDetail) target;
    if (StringUtils.isBlank(projectDetail.getProject().getName())) {
        errors.rejectValue(NAME, IdeaExchangeErrorCodes.FIELD_REQUIRED,
                IdeaExchangeConstants.Messages.REQUIRED_FIELD);
        log.warn("Validation Error : " + NAME + " -: " + IdeaExchangeConstants.Messages.REQUIRED_FIELD);
    }//w  w  w. j av a 2s . c  o m
    if (!StringUtils.isBlank(projectDetail.getProject().getName())
            && projectDetail.getProject().getName().trim().length() > LENGTH_500) {
        errors.rejectValue(NAME, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
        log.warn("Validation Error : " + NAME + " -: "
                + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
    }
    if (!StringUtils.isBlank(projectDetail.getProject().getDescription())
            && projectDetail.getProject().getDescription().trim().length() > LENGTH_3000) {
        errors.rejectValue(DESCRIPTION, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
        log.warn("Validation Error : " + DESCRIPTION + " -: "
                + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
    }
    List<Developer> developers = projectDetail.getDevelopers();
    if (developers != null) {
        for (Developer developer : developers) {
            if (!StringUtils.isBlank(developer.getName()) && developer.getName().trim().length() > LENGTH_50) {
                errors.rejectValue(DEVELOPER_NAME, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                        IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
                log.warn("Validation Error : " + DEVELOPER_NAME + " -: "
                        + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
            }
            if (!StringUtils.isBlank(developer.getEmailId())
                    && developer.getEmailId().trim().length() > LENGTH_50) {
                errors.reject(IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                        DEVELOPER_EMAIL + ":" + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
                log.warn("Validation Error : " + DEVELOPER_EMAIL + " -: "
                        + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
            }
        }
    }

    if (log.isDebugEnabled()) {

        if (errors.hasErrors()) {
            log.debug("Validator found " + errors.getErrorCount() + " errors");
            for (Iterator<FieldError> iterator = errors.getFieldErrors().iterator(); iterator.hasNext();) {
                FieldError fieldError = iterator.next();
                log.debug("Error found in field: " + fieldError.getField() + " Message :"
                        + fieldError.getDefaultMessage());
            }
        } else {
            log.debug("Validator found no errors");
        }

    }
}

From source file:org.frat.common.exception.BindingResultExceptionHandler.java

/**
 * /*from   ww  w.  j  ava  2s.  com*/
 * Description: set the result dto.
 * 
 * @param locale
 * 
 * @param constraintViolation
 * @throws NoSuchFieldException
 */
private void setResultDto(BindingResult bindingResult, List<ValidationResultDto> errorData, String formId,
        boolean notManually) {
    List<FieldError> fieldErros = bindingResult.getFieldErrors();
    String beanName = bindingResult.getObjectName();
    Object rootObject = bindingResult.getTarget();
    Class<?> rootClass = rootObject.getClass();
    if (fieldErros != null && fieldErros.size() > 0) {
        for (FieldError fieldError : fieldErros) {
            final String fieldName = fieldError.getField();
            String message = fieldError.getDefaultMessage();
            final String errorCode = fieldError.getCode();
            if (StringUtils.isEmpty(message)) {
                message = MessageUtil.getMessage(StringUtils.isNotEmpty(errorCode) ? errorCode : message);
            }
            setFieldErrorMap(fieldName, beanName, rootClass, errorData, message, formId, notManually);
        }
    }
}

From source file:br.com.javatar.examples.handler.BindExceptionExceptionHandler.java

@Override
public ValidationErrorMessage createBody(BindException ex, HttpServletRequest req) {

    ErrorMessage tmpl = super.createBody(ex, req);
    ValidationErrorMessage msg = new ValidationErrorMessage(tmpl);

    for (FieldError violation : ex.getFieldErrors()) {
        String pathNode = violation.getField();

        // path is probably useful only for properties (fields)
        msg.addError(pathNode, convertToString(violation.getRejectedValue()), violation.getDefaultMessage());
    }/*from  ww  w.j av  a2  s.co m*/

    return msg;
}

From source file:ch.ralscha.extdirectspring.bean.ExtDirectResponseBuilder.java

/**
 * Adds an "errors" property in the response if there are any errors in the
 * bindingResult. Sets the success flag to false if there are errors.
 *
 * @param locale/*from ww w .j  ava2  s.  co m*/
 * @param messageSource
 * @param bindingResult
 * @return this instance
 */
public ExtDirectResponseBuilder addErrors(Locale locale, MessageSource messageSource,
        final BindingResult bindingResult) {
    if (bindingResult != null && bindingResult.hasFieldErrors()) {
        Map<String, List<String>> errorMap = new HashMap<String, List<String>>();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            String message = fieldError.getDefaultMessage();
            if (messageSource != null) {
                Locale loc = locale != null ? locale : Locale.getDefault();
                message = messageSource.getMessage(fieldError.getCode(), fieldError.getArguments(), loc);
            }
            List<String> fieldErrors = errorMap.get(fieldError.getField());

            if (fieldErrors == null) {
                fieldErrors = new ArrayList<String>();
                errorMap.put(fieldError.getField(), fieldErrors);
            }

            fieldErrors.add(message);
        }
        if (errorMap.isEmpty()) {
            addResultProperty("success", Boolean.TRUE);
        } else {
            addResultProperty("errors", errorMap);
            addResultProperty("success", Boolean.FALSE);
        }
    }
    return this;
}

From source file:cs544.wamp_blog_engine.controller.UserController.java

@RequestMapping(value = "/users/{id}", method = RequestMethod.POST)
public String updateUser(@Valid User user, BindingResult result, @PathVariable int id, HttpSession session) {
    //System.out.println("Update");
    if (!result.hasErrors()) {
        //System.out.println("done");
        session.setAttribute("user", user);
        userService.updateUserInfo(id, user);
        return "redirect:/users";
    } else {//  ww  w.j  ava2 s  .c om
        for (FieldError err : result.getFieldErrors()) {
            System.out.println(err.getField() + ": " + err.getDefaultMessage());
        }
        System.out.println("err");
        return "userDetail";
    }
}

From source file:com.oak_yoga_studio.controller.FacultyController.java

@RequestMapping(value = "/updateFacultyProfile", method = RequestMethod.POST)
public String updateUser(@Valid Faculty facultyUpdate, BindingResult result, HttpSession session,
        RedirectAttributes flashAttr, @RequestParam("file") MultipartFile file) {
    String view = "redirect:/";

    if (!result.hasErrors()) {
        int Id = ((Faculty) session.getAttribute("loggedUser")).getId();
        Faculty faculty = facultyService.getFacultyById(Id);

        faculty.setFirstName(facultyUpdate.getFirstName());
        faculty.setLastName(facultyUpdate.getLastName());
        //System.out.println("Date of Birth" + customerUpdate.getDateOfBirth());
        //customer.setDateOfBirth(customerUpdate.getDateOfBirth());
        faculty.setEmail(facultyUpdate.getEmail());

        try {/*from ww w  . ja  v  a 2s  .c  o m*/
            System.out.println("Imageeeeeeeeeee - " + file.getBytes());
            if (file.getBytes().length != 0) {
                faculty.setProfilePicture(file.getBytes());
            }
        } catch (IOException ex) {

        }

        facultyService.updateFaculty(Id, faculty);
    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println(
                    "Error from UpdateProfileController " + err.getField() + ": " + err.getDefaultMessage());
        }
        System.out.println("err");
    }
    return "redirect:/facultyProfile";
}

From source file:com.google.ie.common.validation.IdeaValidator.java

@Override
public void validate(Object target, Errors errors) {
    Idea idea = (Idea) target;/*from   ww  w .ja  va2s.  c o  m*/
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, TITLE, IdeaExchangeErrorCodes.FIELD_REQUIRED,
            IdeaExchangeConstants.Messages.REQUIRED_FIELD);
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, DESCRIPTION, IdeaExchangeErrorCodes.FIELD_REQUIRED,
            IdeaExchangeConstants.Messages.REQUIRED_FIELD);

    if (!idea.isIdeaRightsGivenUp()) {
        errors.rejectValue(IDEA_RIGHTS_GIVEN_UP, IdeaExchangeErrorCodes.FIELD_ALWAYS_TRUE,
                IdeaExchangeConstants.Messages.FIELD_ALWAYS_TRUE);
        log.warn("Validation Error : " + IDEA_RIGHTS_GIVEN_UP + " -: "
                + IdeaExchangeConstants.Messages.FIELD_ALWAYS_TRUE);
    }
    if (!idea.isIpGivenUp()) {
        errors.rejectValue(IP_GIVEN_UP, IdeaExchangeErrorCodes.FIELD_ALWAYS_TRUE,
                IdeaExchangeConstants.Messages.FIELD_ALWAYS_TRUE);
        log.warn("Validation Error : " + IP_GIVEN_UP + " -: "
                + IdeaExchangeConstants.Messages.FIELD_ALWAYS_TRUE);
    }
    if (!StringUtils.isBlank(idea.getTitle()) && idea.getTitle().trim().length() > LENGTH_500) {
        errors.rejectValue(TITLE, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
        log.warn("Validation Error : " + TITLE + " -: "
                + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
    }
    if (!StringUtils.isBlank(idea.getDescription()) && idea.getDescription().trim().length() > LENGTH_3000) {
        errors.rejectValue(DESCRIPTION, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
        log.warn("Validation Error : " + DESCRIPTION + " -: "
                + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
    }
    if (!StringUtils.isBlank(idea.getIdeaSummary()) && idea.getIdeaSummary().trim().length() > LENGTH_3000) {
        errors.rejectValue(IDEA_SUMMARY, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
        log.warn("Validation Error : " + IDEA_SUMMARY + " -: "
                + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
    }
    if (!StringUtils.isBlank(idea.getMonetization()) && idea.getMonetization().trim().length() > LENGTH_500) {
        errors.rejectValue(MONETIZATION, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
        log.warn("Validation Error : " + MONETIZATION + " -: "
                + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
    }
    if (!StringUtils.isBlank(idea.getTargetAudience())
            && idea.getTargetAudience().trim().length() > LENGTH_500) {
        errors.rejectValue(TARGET_AUDIENCE, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
        log.warn("Validation Error : " + TARGET_AUDIENCE + " -: "
                + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
    }
    if (!StringUtils.isBlank(idea.getCompetition()) && idea.getCompetition().trim().length() > LENGTH_500) {
        errors.rejectValue(COMPETITION, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
        log.warn("Validation Error : " + COMPETITION + " -: "
                + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
    }
    if (idea.getTags() != null && idea.getTags().length() > ZERO) {
        ValidationUtils.invokeValidator(stringValidatorForTagTitle, idea.getTags(), errors);

    }
    if (log.isDebugEnabled()) {
        if (errors.hasErrors()) {
            log.debug("Validator found " + errors.getErrorCount() + " errors");
            for (Iterator<FieldError> iterator = errors.getFieldErrors().iterator(); iterator.hasNext();) {
                FieldError fieldError = iterator.next();
                log.debug("Error found in field: " + fieldError.getField() + " Message :"
                        + fieldError.getDefaultMessage());
            }
        } else {
            log.debug("Validator found no errors");
        }

    }
}