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:cs544.wamp_blog_engine.controller.UserController.java

@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String add(@Valid User user, BindingResult result, HttpSession session, RedirectAttributes flashAttr,
        @RequestParam("file") MultipartFile file) {
    String view = "redirect:/";
    System.out.println("userController Add");

    if (!result.hasErrors()) {
        try {/*from   www .j av  a  2s. com*/
            user.setProfilepic(file.getBytes());
        } catch (IOException ex) {
            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
        }
        userService.addUser(user);
        session.removeAttribute("credential");
        flashAttr.addFlashAttribute("successfulSignup",
                "User signed up succesfully. please  log in to proceed");
        User u = (User) session.getAttribute("loggedUser");
        if (u != null && u.getUserCredential().isAdmin()) {
            view = "redirect:/settings";
        }
    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println("Error:" + err.getField() + ":" + err.getDefaultMessage());
        }
        view = "addUser";
    }
    return view;
}

From source file:com.simplecrud.controller.RegisteredMemberController.java

/**
 *
 * @param member/* w  w w  . java  2 s. c  o m*/
 * @param result
 * @param model
 * @param request
 * @return
 */
@RequestMapping(value = "/updateuser", method = RequestMethod.POST)
public ModelAndView validateandUpdateUser(@Valid @ModelAttribute("UpdateMemberForm") ValidateMember member,
        BindingResult result, Model model, HttpServletRequest request) {

    String id = request.getParameter("id");

    FormStatus sFormStatus = new FormStatus();

    //if validated form has errors
    if (result.hasErrors()) {

        //handle errors in the inputs
        List<FieldError> errors = result.getFieldErrors();
        for (FieldError error : errors) {
            System.out.println(error.getField() + " - " + error.getDefaultMessage());

            if ("username".equals(error.getField())) {
                //set error message in username input
                sFormStatus.setsUsername(error.getDefaultMessage());
                sFormStatus.setsUsernameInput("has-error");
            }

            if ("password".equals(error.getField())) {
                //set error message in password input
                sFormStatus.setsPassword(error.getDefaultMessage());
                sFormStatus.setsPasswordInput("has-error");
            }

            if ("email".equals(error.getField())) {
                //set error message in email input
                sFormStatus.setsEmail(error.getDefaultMessage());
                sFormStatus.setsEmailInput("has-error");
            }

        }
        System.out.println(result.getFieldErrors());
        return new ModelAndView("redirect:/registeredmember.html?" + "&ErrorUsername="
                + sFormStatus.getsUsername() + "" + "&ErrorPassword=" + sFormStatus.getsPassword() + ""
                + "&ErrorEmail=" + sFormStatus.getsEmail() + "" + "&response=error&id=" + id + "");

    } else {

        String sUsername = request.getParameter("username");
        String sPassword = request.getParameter("password");
        String sEmail = request.getParameter("email");
        Long lUser_id = Long.parseLong(id);

        //try to save the form
        try {
            System.out.println(sUsername + " username" + sPassword + sEmail + lUser_id);
            Object update_result = userDao.updateUserInfo(lUser_id, sUsername, sPassword, sEmail);

            return new ModelAndView("redirect:/registeredmember.html?classerror=has-success&response="
                    + update_result + "&id=" + id + "");

        } catch (Exception e) {
            System.out.println(e.getMessage() + " Error updating form");
            return new ModelAndView(
                    "redirect:/registeredmember.html?response=The Data you have typed is already exist, try another one.&classerror=has-error&id="
                            + id + "");
        }

    }

}

From source file:com.autoupdater.server.controllers.FrontEndAPIController.java

/**
 * Handles errors that occurred during remote upload.
 * /*from   w  w w.  j  a  v a2  s  . c om*/
 * @param response
 *            response to send
 * @param result
 *            result of validation
 */
private void handleErrorDuringRemoteUpload(HttpServletResponse response, BindingResult result) {
    int errorCode;
    List<FieldError> errors;

    if (result.hasFieldErrors("username")) {
        errorCode = SC_UNAUTHORIZED;
        errors = result.getFieldErrors("username");
    } else if (result.hasFieldErrors("program")) {
        errorCode = SC_FORBIDDEN;
        errors = result.getFieldErrors("username");
    } else {
        errorCode = SC_BAD_REQUEST;
        errors = result.getFieldErrors();
    }

    StringBuilder builder = new StringBuilder();
    for (FieldError error : errors)
        builder.append(error.getDefaultMessage()).append('\n');
    sendError(response, errorCode, builder.toString());
}

From source file:com.google.ie.web.controller.ProjectCommentController.java

/**
 * Handles request to add comment on a Project.
 * // w ww .j  a v a 2s . c o  m
 * @param projectComment key of the Project on which the comment is to be
 *        added.
 * @param user the User object
 * @throws IOException
 */
@RequestMapping(value = "/postProjectComments", method = RequestMethod.POST)
public void postCommentOnProject(HttpServletRequest request, @ModelAttribute ProjectComment projectComment,
        BindingResult result, Map<String, Object> map, @RequestParam String recaptchaChallengeField,
        @RequestParam String recaptchaResponseField, HttpSession session) throws IOException {
    ViewStatus viewStatus = new ViewStatus();
    Boolean captchaValidation = reCaptchaUtility.verifyCaptcha(request.getRemoteAddr(), recaptchaChallengeField,
            recaptchaResponseField);
    /* call CommentValidator to validate input ProjectComment object */
    getCommentValidator().validate(projectComment, result);
    if (result.hasErrors() || !captchaValidation) {
        logger.warn("Comment object has " + result.getErrorCount() + " validation errors");
        viewStatus.setStatus(WebConstants.ERROR);
        /* Add a message if the captcha validation fails */
        if (!captchaValidation) {
            viewStatus.addMessage(WebConstants.CAPTCHA, WebConstants.CAPTCHA_MISMATCH);
        }
        /* Iterate the errors and add a message for each error */
        for (Iterator<FieldError> iterator = result.getFieldErrors().iterator(); iterator.hasNext();) {
            FieldError fieldError = iterator.next();
            viewStatus.addMessage(fieldError.getField(), fieldError.getDefaultMessage());
            logger.warn("Error found in field: " + fieldError.getField() + " Message :"
                    + fieldError.getDefaultMessage());
        }

    } else {
        User user = (User) session.getAttribute(WebConstants.USER);
        Comment comment = commentService.addComment(projectComment, user);
        if (comment != null) {
            viewStatus.setStatus(WebConstants.SUCCESS);
            viewStatus.addMessage(WebConstants.COMMENTS, WebConstants.COMMENT_SUCCESSFULL);
        } else {
            viewStatus.setStatus(WebConstants.ERROR);
            viewStatus.addMessage(WebConstants.COMMENTS, WebConstants.COMMENT_FAILED);
        }
    }
    map.remove("projectComment");
    map.put(WebConstants.VIEW_STATUS, viewStatus);
}

From source file:org.mifos.loan.service.StandardLoanServiceTest.java

private void assertExpectedError(MifosServiceException mifosServiceException, String fieldName,
        String defaultErrorMessage) {
    Assert.assertEquals(1, mifosServiceException.getErrors().getErrorCount());
    FieldError error = (FieldError) mifosServiceException.getErrors().getFieldErrors().get(0);
    Assert.assertEquals(error.getField(), fieldName);
    Assert.assertEquals(error.getDefaultMessage(), defaultErrorMessage);
}

From source file:com.sra.biotech.submittool.persistence.client.SubmitExceptionHandler.java

@ExceptionHandler({ InvalidRequestException.class })
protected ResponseEntity<Object> handleInvalidRequest(RuntimeException e, WebRequest request) {
    InvalidRequestException ire = (InvalidRequestException) e;
    List<FieldErrorResource> fieldErrorResources = new ArrayList<>();

    List<FieldError> fieldErrors = ire.getErrors().getFieldErrors();
    for (FieldError fieldError : fieldErrors) {
        FieldErrorResource fieldErrorResource = new FieldErrorResource();
        fieldErrorResource.setResource(fieldError.getObjectName());
        fieldErrorResource.setField(fieldError.getField());
        fieldErrorResource.setCode(fieldError.getCode());
        fieldErrorResource.setMessage(fieldError.getDefaultMessage());
        fieldErrorResources.add(fieldErrorResource);
    }/*from   w  ww .  j  a v  a2s. c  o m*/

    ErrorResource error = new ErrorResource("InvalidRequest", ire.getMessage());
    error.setFieldErrors(fieldErrorResources);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    return handleExceptionInternal(e, error, headers, HttpStatus.UNPROCESSABLE_ENTITY, request);
}

From source file:com.springsource.greenhouse.signup.SignupController.java

private List<Map<String, String>> getErrorsMap(BindingResult formBinding) {
    List<FieldError> fieldErrors = formBinding.getFieldErrors();
    List<Map<String, String>> errors = new ArrayList<Map<String, String>>(fieldErrors.size());
    for (FieldError fieldError : fieldErrors) {
        Map<String, String> fieldErrorMap = new HashMap<String, String>();
        fieldErrorMap.put("field", fieldError.getField());
        fieldErrorMap.put("code", fieldError.getCode());
        fieldErrorMap.put("message", fieldError.getDefaultMessage());
        errors.add(fieldErrorMap);//from   w ww.  j  av a2  s .  c o m
    }
    return errors;
}

From source file:com.mmj.app.web.controller.BaseController.java

/**
 * ??/*w  w w  . ja v a  2 s .c  o m*/
 * 
 * @param result
 * @return
 */
public Result showErrors(BindingResult result) {
    StringBuffer errorsb = new StringBuffer();
    if (result.hasErrors()) {
        for (FieldError error : result.getFieldErrors()) {
            errorsb.append(error.getField());
            errorsb.append(error.getDefaultMessage());
            errorsb.append("|");
        }
        String errorsr = errorsb.toString().substring(0, errorsb.toString().length() - 1);
        Result.failed(errorsr.replaceAll("null", StringUtils.EMPTY));
    }
    return Result.success();
}

From source file:org.jtalks.common.web.dto.ValidationResults.java

/**
 * This method populates field errors from the specified {@link BindingResult} to the {@code fieldErrors} structure
 *
 * @param bindingResult Binding result to populate field errors from
 *//*from   ww w . ja v  a2 s  .  c om*/
private void populateFieldErrors(BindingResult bindingResult) {
    fieldErrors = new HashMap<String, List<String>>();
    for (FieldError error : bindingResult.getFieldErrors()) {
        List<String> currentFieldErrors = fieldErrors.get(error.getField());
        if (currentFieldErrors == null) {
            currentFieldErrors = new ArrayList<String>();
        }

        currentFieldErrors.add(error.getDefaultMessage());
        fieldErrors.put(error.getField(), currentFieldErrors);
    }
}

From source file:com.teamd.taxi.controllers.admin.DriverAdminController.java

@RequestMapping(value = "/driver-create", method = RequestMethod.POST)
@ResponseBody//from   w ww  . ja  va  2  s .  c om
public AdminResponseModel<String> addDriver(@Valid CreateDriverModel driverModel, BindingResult bindingResult) {
    System.out.println(driverModel);
    AdminResponseModel<String> response = new AdminResponseModel<>();
    if (bindingResult.hasErrors()) {
        StringBuilder errors = new StringBuilder();
        for (FieldError fieldError : validateUtil.filterErrors(bindingResult.getFieldErrors())) {
            errors.append("<p>");
            errors.append(fieldError.getDefaultMessage());
            errors.append("</p>");
        }
        return response.setContent(errors.toString());
    }
    driverService.createDriverAccount(driverModel.toDriver());
    response.setResultSuccess().setContent(env.getRequiredProperty(MESSAGE_DRIVER_SUCCESS_CREATE));
    return response;
}