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:com.teamd.taxi.controllers.admin.DriverAdminController.java

@RequestMapping(value = "/driver-update", method = RequestMethod.POST)
@ResponseBody//from  w w w  .j  a v  a 2s. c o  m
public AdminResponseModel<String> updateDriver(@Valid UpdateDriverModel driverModel,
        BindingResult bindingResult) {
    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.updateDriverAccount(driverModel);
    response.setResultSuccess().setContent(env.getRequiredProperty(MESSAGE_DRIVER_SUCCESS_UPDATE));
    return response;
}

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

/**
 * Handles request to add comment on Idea.
 * /*ww w. j  a  va2  s  .  c o  m*/
 * @param ideaComment key of the Idea on which the comment is to be added.
 * @param user the User object
 * @throws IOException
 */
@RequestMapping(value = "/post", method = RequestMethod.POST)
public void postCommentOnIdea(HttpServletRequest request, HttpSession session,
        @ModelAttribute IdeaComment ideaComment, BindingResult result, Map<String, Object> map,
        @RequestParam String recaptchaChallengeField, @RequestParam String recaptchaResponseField)
        throws IOException {

    /*
     * get captcha fields from request call CommentValidator to validate
     * input IdeaComment object
     */
    ViewStatus viewStatus = new ViewStatus();
    Boolean captchaValidation = reCaptchaUtility.verifyCaptcha(request.getRemoteAddr(), recaptchaChallengeField,
            recaptchaResponseField);

    new CommentValidator().validate(ideaComment, result);
    /*
     * check for validation or captcha error and if error occured display
     * the error messages.
     */
    if (result.hasErrors() || !captchaValidation) {
        logger.warn("Comment object has " + result.getErrorCount() + " validation errors");
        viewStatus.setStatus(WebConstants.ERROR);
        if (!captchaValidation) {
            viewStatus.addMessage(WebConstants.CAPTCHA, WebConstants.CAPTCHA_MISMATCH);
        }
        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);
        /* Call comment service to add new comment */
        Comment comment = commentService.addComment(ideaComment, 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("ideaComment");
    map.put(WebConstants.VIEW_STATUS, viewStatus);
}

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

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

    if (!result.hasErrors()) {
        try {//  ww  w. j  a v  a  2  s . c  o  m
            faculty.setProfilePicture(file.getBytes());
        } catch (IOException ex) {
            //Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
        }
        faculty.getCredential().setActive(false);
        faculty.setActive(false);
        facultyServcie.addFaculty(faculty);
        session.removeAttribute("credential");
        flashAttr.addFlashAttribute("successful registered",
                "Faculty signed up succesfully. please  log in to proceed"); //           Customer c=(Customer) session.getAttribute("loggedCustomer");

    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println("Error:" + err.getField() + ":" + err.getDefaultMessage());
        }
        view = "addFaculty";
    }
    return view;
}

From source file:org.centralperf.controller.RunController.java

/**
 * Create a new Run//from   w w  w  . j a  v a 2  s  .c  om
 * @param projectId ID of the project (from URI)
 * @param run   The Run to create
 * @param result   BindingResult to check if binding raised some errors
 * @param model   Model prepared for the new project form view in case of errors
 * @return Redirection to the run detail page once the run has been created 
 */
@RequestMapping(value = "/project/{projectId}/run/new", method = RequestMethod.POST)
public String addRun(@PathVariable("projectId") Long projectId, @ModelAttribute("run") @Valid Run run,
        BindingResult result, Model model, RedirectAttributes redirectAttrs) {
    if (result.hasErrors()) {
        String errorMessage = "Error creating Run : ";
        for (FieldError error : result.getFieldErrors()) {
            errorMessage += "Field " + error.getField() + ",  " + error.getDefaultMessage() + " ( "
                    + error.getRejectedValue() + ")";
        }
        redirectAttrs.addFlashAttribute("error", errorMessage);
        return "redirect:/project/" + projectId + "/detail";
    }
    ScriptVersion scriptVersion = scriptVersionRepository.findOne(run.getScriptVersion().getId());
    run.setScriptVersion(scriptVersion);
    runRepository.save(run);
    return "redirect:/project/" + projectId + "/run/" + run.getId() + "/detail";
}

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

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

    if (!result.hasErrors()) {
        try {//from ww  w  . j  ava  2s  . c om
            customer.setProfilePicture(file.getBytes());
        } catch (IOException ex) {
            Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
        }
        customerService.addCustomer(customer);
        session.removeAttribute("credential");
        flashAttr.addFlashAttribute("successfulSignup",
                "Customer signed up succesfully. please  log in to proceed");

    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println("Error:" + err.getField() + ":" + err.getDefaultMessage());
        }
        view = "addCustomer";
    }
    return view;
}

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

@RequestMapping(value = "/updateAddress", method = RequestMethod.POST)
public String updateAddress(@Valid Address addressUpdate, BindingResult result, HttpSession session,
        RedirectAttributes flashAttr) {/*from ww w  . j  av  a  2  s. co  m*/
    String view = "redirect:/";

    if (!result.hasErrors()) {
        int Id = ((Customer) session.getAttribute("loggedUser")).getId();
        Address address = customerService.getCutomerAdress(Id);

        address.setStreet(addressUpdate.getStreet());
        address.setCity(addressUpdate.getCity());
        address.setZipCode(addressUpdate.getZipCode());
        address.setState(addressUpdate.getState());
        if (address.getId() == 0) {
            addressService.addAddress(address);
        } else {
            addressService.updateAddress(address);
        }
    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println(
                    "Error from UpdateProfileController " + err.getField() + ": " + err.getDefaultMessage());
        }
        System.out.println("err");
    }
    return "redirect:/editProfile";
}

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

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

    if (!result.hasErrors()) {
        int Id = ((Customer) session.getAttribute("loggedUser")).getId();
        Customer customer = customerService.getCustomerById(Id);

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

        try {//from  ww  w. ja va 2  s  .c  o m

            if (file.getBytes().length != 0) {
                customer.setProfilePicture(file.getBytes());
            }
        } catch (IOException ex) {

        }

        customerService.updateCustomer(Id, customer);
    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println(
                    "Error from UpdateProfileController " + err.getField() + ": " + err.getDefaultMessage());
        }
        System.out.println("err");
    }
    return "redirect:/editProfile";
}

From source file:com.ignou.aadhar.controllers.CitizenController.java

@RequestMapping(value = "/create", method = RequestMethod.POST)
public String createCitizen(@Valid Citizen newCitizen, BindingResult result, Model model) throws Exception {

    /* Check if there was any error while binding the citizen object */
    if (result.hasErrors()) {

        /* There was some error while binding the form data to java objects.
         * Lets re-direct the user back to the form.
         *//*from  ww w .  j a  v  a2  s .  com*/
        for (FieldError error : result.getFieldErrors()) {
            System.out.println("--> " + error.getField() + " - " + error.getDefaultMessage());
        }

        model.addAttribute("newCitizen", newCitizen);
        model.addAttribute("genders", citizenService.getGenders());
        model.addAttribute("banks", bankService.list());
        model.addAttribute("accessRoles", citizenService.getAccessRoles());
        model.addAttribute("states", stateService.list());

        return "citizen/create";
    }

    /* Let's generate the UID for this citizen */
    newCitizen.setUid(UIDGenerator.generateUID(UIDTypes.CITIZEN));

    /* Also, set the created date for now's date */
    newCitizen.setCreated(new Date());

    /* During registration, the status would be pending */
    newCitizen.setStatus(UIDStates.PENDING.getCode());

    /* No error while binding the form data to java objects */
    /* Lets save the new Citizen into the database */
    Citizen dbCitizen = createCitizenDetails(newCitizen);

    try {
        EmailSender emailSender = new EmailSender();
        emailSender.send("justdpk@gmail.com", "Registration Successful", "UID Registration Successful.");
    } catch (Exception e) {
        e.printStackTrace();
    }

    /* Citizen added successfully. Lets re-direct to view page */
    return "redirect:/citizen/" + dbCitizen.getId();
}

From source file:com.iflytek.edu.cloud.frame.spring.DefaultHandlerExceptionResolver.java

/**
 * ??//from  ww w. j  av a 2  s  .c om
 *
 * @param allErrors
 * @param locale
 * @param subErrorType
 * @return
 */
private MainError getBusinessParameterMainError(List<ObjectError> allErrors, Locale locale,
        SubErrorType subErrorType) {
    MainError mainError = SubErrors.getMainError(subErrorType, locale);
    for (ObjectError objectError : allErrors) {
        if (objectError instanceof FieldError) {
            FieldError fieldError = (FieldError) objectError;
            SubErrorType tempSubErrorType = INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.get(fieldError.getCode());
            if (tempSubErrorType == subErrorType) {
                SubError subError = SubErrors.getSubError(tempSubErrorType.value(), locale,
                        fieldError.getField(), fieldError.getRejectedValue(), fieldError.getDefaultMessage());
                mainError.addSubError(subError);
            }
        }
    }
    return mainError;
}

From source file:org.jasig.schedassist.web.register.Registration.java

/**
 * Validate after the preferences related fields have been set.
 * //from   www. j a  v  a 2 s. co m
 * Delegates to a {@link PreferencesFormBackingObjectValidator}.
 * @param context
 */
public void validateSetPreferences(final ValidationContext context) {
    MessageContext messages = context.getMessageContext();

    PreferencesFormBackingObject command = this.toPreferencesFormBackingObject();

    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(command, "registration");
    preferencesValidator.validate(command, errors);

    if (errors.hasErrors()) {
        for (FieldError error : errors.getFieldErrors()) {
            messages.addMessage(new MessageBuilder().error().source(error.getField())
                    .defaultText(error.getDefaultMessage()).build());
        }
    }
}