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:org.duracloud.account.app.controller.UserController.java

@Transactional
@RequestMapping(value = { CHANGE_PASSWORD_MAPPING }, method = RequestMethod.POST)
public ModelAndView changePassword(@PathVariable String username,
        @ModelAttribute(CHANGE_PASSWORD_FORM_KEY) @Valid ChangePasswordForm form, BindingResult result,
        Model model) throws Exception {

    DuracloudUser user = this.userService.loadDuracloudUserByUsername(username);

    // check for errors
    if (!result.hasErrors()) {
        log.info("changing user password for {}", username);
        Long id = user.getId();/*from  www.  jav a 2  s .  c o  m*/
        try {
            this.userService.changePassword(id, form.getOldPassword(), false, form.getPassword());
            return new ModelAndView(formatUserRedirect(username));
        } catch (InvalidPasswordException e) {
            result.addError(
                    new FieldError(CHANGE_PASSWORD_FORM_KEY, "oldPassword", "The old password is not correct"));
        }
    }

    log.debug("password form has errors for {}: returning...", username);
    addUserToModel(user, model);

    UserProfileEditForm editForm = new UserProfileEditForm();

    editForm.setFirstName(user.getFirstName());
    editForm.setLastName(user.getLastName());
    editForm.setEmail(user.getEmail());
    editForm.setSecurityQuestion(user.getSecurityQuestion());
    editForm.setSecurityAnswer(user.getSecurityAnswer());
    model.addAttribute(USER_PROFILE_FORM_KEY, editForm);
    return new ModelAndView(USER_EDIT_VIEW, model.asMap());

}

From source file:com.devnexus.ting.web.controller.cfp.CallForPapersController.java

private CfpSpeakerImage processPicture(MultipartFile picture, BindingResult bindingResult) {
    CfpSpeakerImage cfpSpeakerImage = null;
    byte[] pictureData = null;

    try {//from ww w.  j  ava  2 s .  c o m
        pictureData = picture.getBytes();
    } catch (IOException e) {
        LOGGER.error("Error processing Image.", e);
        bindingResult
                .addError(new FieldError("cfpSubmissionSpeaker", "pictureFile", "Error processing Image."));
        return null;
    }

    if (pictureData != null && picture.getSize() > 0) {

        ByteArrayInputStream bais = new ByteArrayInputStream(pictureData);
        BufferedImage image;
        try {
            image = ImageIO.read(bais);
        } catch (IOException e) {
            LOGGER.error("Error processing Image.", e);
            bindingResult
                    .addError(new FieldError("cfpSubmissionSpeaker", "pictureFile", "Error processing Image."));
            return null;
        }

        if (image == null) {
            //FIXME better way?
            final String fileSizeFormatted = FileUtils.byteCountToDisplaySize(picture.getSize());
            LOGGER.warn(String.format("Cannot parse file '%s' (Content Type: %s; Size: %s) as image.",
                    picture.getOriginalFilename(), picture.getContentType(), fileSizeFormatted));
            bindingResult.addError(new FieldError("cfpSubmissionSpeaker", "pictureFile",
                    String.format(
                            "Did you upload a valid image? We cannot parse file '%s' (Size: %s) as image file.",
                            picture.getOriginalFilename(), fileSizeFormatted)));
            return null;
        }

        int imageHeight = image.getHeight();
        int imageWidth = image.getWidth();

        if (imageHeight < 360 && imageWidth < 360) {
            bindingResult.addError(new FieldError("cfpSubmissionSpeaker", "pictureFile", String.format(
                    "Your image '%s' (%sx%spx) is too small. Please provide an image of at least 360x360px.",
                    picture.getOriginalFilename(), imageWidth, imageHeight)));
        }

        cfpSpeakerImage = new CfpSpeakerImage();

        cfpSpeakerImage.setFileData(pictureData);
        cfpSpeakerImage.setFileModified(new Date());
        cfpSpeakerImage.setFileSize(picture.getSize());
        cfpSpeakerImage.setName(picture.getOriginalFilename());
        cfpSpeakerImage.setType(picture.getContentType());

        return cfpSpeakerImage;
    }

    return null;
}

From source file:ch.javaee.basicMvc.web.controller.UserController.java

@RequestMapping(value = "/public/signup_confirm", method = RequestMethod.POST)
@Transactional//  w  ww. ja  v a2 s. c o m
public String createUser(Model model, @ModelAttribute("user") @Valid UserForm form, BindingResult result,
        @RequestParam(value = "recaptcha_challenge_field", required = false) String challangeField,
        @RequestParam(value = "recaptcha_response_field", required = false) String responseField,
        ServletRequest servletRequest) {
    logger.debug("Enter: createUser");
    if (reCaptcha != null) {
        String remoteAdress = servletRequest.getRemoteAddr();
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAdress, challangeField,
                responseField);
        if (!reCaptchaResponse.isValid()) {
            this.create(model);
            return "view/public/signup";
        }
    }
    if (!result.hasErrors()) {

        // check if email already exists
        if (userRepository.isEmailAlreadyExists(form.getEmail())) {
            FieldError fieldError = new FieldError("user", "email", "email already exists");
            result.addError(fieldError);
            return "view/public/signup";
        }
        User user = new User();
        Md5PasswordEncoder encoder = new Md5PasswordEncoder();
        user.setUsername(form.getUsername());
        user.setEmail(form.getEmail());
        user.setEnabled(false);

        user.setPassword(encoder.encodePassword(form.getPassword(), user.getEmail()));
        Role role = new Role();
        role.setUser(user);
        role.setRole(2);

        SecurityCode securityCode = new SecurityCode();
        securityCode.setUser(user);
        securityCode.setTimeRequest(new Date());
        securityCode.setTypeActivationEnum(TypeActivationEnum.NEW_ACCOUNT);
        securityCode.setCode(SecureUtility.generateRandomCode());
        user.setRole(role);
        user.setSecurityCode(securityCode);

        userRepository.saveUser(user);
        //securityCodeRepository.persist(securityCode);
        mailSenderService.sendAuthorizationMail(user, user.getSecurityCode());

    } else {
        logger.debug("signup error");
        this.create(model);
        return "view/public/signup";

    }
    logger.debug("Exit: createUser");
    return "view/public/mailSent";
}

From source file:com.devnexus.ting.web.controller.EvaluationController.java

@RequestMapping(value = "/s/evaluations/add", method = RequestMethod.POST)
public String editEvent(@Valid Evaluation evaluation, BindingResult bindingResult, ModelMap model,
        HttpServletRequest request, RedirectAttributes redirectAttributes) {

    if (request.getParameter("cancel") != null) {
        return "redirect:/s/index";
    }/* w  w  w .  j  av  a 2  s .c o  m*/

    final String reCaptchaEnabled = environment.getProperty("recaptcha.enabled");
    final String recaptchaPrivateKey = environment.getProperty("recaptcha.privateKey");

    if (Boolean.valueOf(reCaptchaEnabled)) {
        String remoteAddr = request.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey(recaptchaPrivateKey);

        String challenge = request.getParameter("recaptcha_challenge_field");
        String uresponse = request.getParameter("recaptcha_response_field");
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

        if (!reCaptchaResponse.isValid()) {
            ObjectError error = new ObjectError("error", "Please insert the correct CAPTCHA.");
            bindingResult.addError(error);
            prepareReferenceData(model);
            return "add-evaluation";
        }
    }

    if (bindingResult.hasErrors()) {
        prepareReferenceData(model);
        return "add-evaluation";
    }

    final Event eventFromDb = businessService.getCurrentEvent();

    final Evaluation evaluationToSave = new Evaluation();
    evaluationToSave.setComment(evaluation.getComment());
    evaluationToSave.setEvent(eventFromDb);
    evaluationToSave.setCreatedDate(new Date());
    evaluationToSave.setRating(evaluation.getRating());

    businessService.saveEvaluation(evaluationToSave);

    return "redirect:/s/add-evaluation-success";
}

From source file:com.virtusa.akura.common.controller.ForgotPasswordController.java

/**
 * This method handles the submit user email address request. User enters his/her email address into the
 * given field and click submit./*from w ww  . j  a v a 2  s  .c om*/
 * 
 * @param userLogin - the object to bind the user's email address.
 * @param bindingResult - bind errors to the binding results.
 * @param modMap - model to add attributes.
 * @param session - to get and set session attributes and parameters.
 * @return the view to be return after success or failure.
 * @throws AkuraAppException throws a detailed exception.
 */
@RequestMapping(value = SUBMIT_EMAIL_HTM, method = RequestMethod.POST)
public String submitEmail(@ModelAttribute(USER_LOGIN) UserLogin userLogin, BindingResult bindingResult,
        ModelMap modMap, HttpSession session) throws AkuraAppException {

    String error = null;
    String mailError = null;

    // Validate the email address.
    forgotUserNameValidator.validate(userLogin, bindingResult);

    // if there are errors then go back to the previous page and show the error message.
    if (bindingResult.hasErrors()) {
        return FORGOT_USERNAME;
    }

    // Get the User Login by email address.
    UserLogin user = userService.getAnyUserByEmail(userLogin.getEmail().trim());

    // If there is no user account with the given email address. UserLogin will be empty.
    if (user == null) {

        error = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.FORGOT_USERNAME_ERROR_EMAIL);
        bindingResult.addError(new ObjectError(ERROR, error));
        return FORGOT_USERNAME;

    } else {

        try {
            setMailProprties(user, PropertyReader.getPropertyValue(EMAIL_PROPERTIES, FORGOT_USERNAME_SUBJECT),
                    PropertyReader.getPropertyValue(EMAIL_PROPERTIES, FORGOT_USERANAME_TO_USER));

            // Add the message to Model to pass a value.
            modMap.addAttribute(MESSAGE, AkuraWebConstant.USERNAEM_SEND_SUCCESSFUL_MESSAGE);

        } catch (MailException e) {

            if (e instanceof MailAuthenticationException) {

                mailError = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.EMAIL_AUTHENTICATION_ERROR);
                LOG.error(AkuraWebConstant.EMAIL_AUTHENTICATION_ERROR, e);

            } else if (e.getCause() instanceof MailSendException) {
                mailError = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.EMAIL_SEND_ERROR);
                LOG.error(AkuraWebConstant.EMAIL_SEND_ERROR, e);
            }

            mailError = new ErrorMsgLoader().getErrorMessage(AkuraConstant.EMAIL_ERROR);
            LOG.error(AkuraConstant.EMAIL_ERROR, e);
        } catch (AkuraAppException e) {
            mailError = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.EMAIL_SEND_ERROR);
            LOG.error(AkuraWebConstant.EMAIL_SEND_ERROR, e);
        }

        if (mailError != null) {
            modMap.addAttribute(MAIL_ERRORS, mailError);
        }

    }
    userLogin.setEmail(null);
    return FORGOT_PASSWORD_SUCCESS_OR_ERROR;

}

From source file:mx.edu.um.mateo.activos.web.ActivoController.java

@RequestMapping(value = "/baja", method = RequestMethod.POST)
public String baja(Model modelo, @ModelAttribute BajaActivo bajaActivo, BindingResult bindingResult,
        RedirectAttributes redirectAttributes) {
    log.debug("Dando de baja al activo {}", bajaActivo.getActivo().getId());
    try {/*  w  w w .j a v a2s .  c o  m*/
        Usuario usuario = ambiente.obtieneUsuario();
        String nombre = activoDao.baja(bajaActivo, usuario);

        redirectAttributes.addFlashAttribute("message", "activo.baja.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { nombre });
    } catch (Exception e) {
        log.error("No se pudo dar de baja al activo", e);
        bindingResult
                .addError(new ObjectError("activo", new String[] { "activo.no.baja.message" }, null, null));
        return "activoFijo/activo/ver";
    }

    return "redirect:/activoFijo/activo";
}

From source file:com.web.mavenproject6.controller.UserController.java

@RequestMapping(value = "/public/signup_confirm", method = RequestMethod.POST)
@Transactional//from  www.j a v  a 2 s  .c om
public String createUser(Model model, @ModelAttribute("user") @Valid UserForm form, BindingResult result,
        @RequestParam(value = "recaptcha_challenge_field", required = false) String challangeField,
        @RequestParam(value = "recaptcha_response_field", required = false) String responseField,
        ServletRequest servletRequest) throws GeneralSecurityException {

    if (reCaptcha != null) {
        String remoteAdress = servletRequest.getRemoteAddr();
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAdress, challangeField,
                responseField);
        if (!reCaptchaResponse.isValid()) {
            this.create(model);
            return "thy/public/signup";
        }
    }
    if (!result.hasErrors()) {
        if (userService.isUserExistByEmail(form.getEmail())) {
            FieldError fieldError = new FieldError("user", "email", "email already exists");
            result.addError(fieldError);
            return "thy/public/signup";
        }

        if (userService.isUserExistByLogin(form.getEmail())) {
            FieldError fieldError = new FieldError("user", "username", "login already exists");
            result.addError(fieldError);
            return "thy/public/signup";
        }

        Users user = new Users();

        user.setLogin(form.getUsername());
        user.setEmail(form.getEmail());
        user.setEnabled(false);
        user.setPassword(form.getPassword());

        Role role = new Role();
        role.setUser(user);
        role.setRole(2);

        SecurityCode securityCode = new SecurityCode();
        securityCode.setUser(user);
        securityCode.setTimeRequest(new Date());
        securityCode.setTypeActivationEnum(TypeActivationEnum.NEW_ACCOUNT);
        securityCode.setCode(SecureUtility.generateRandomCode());
        user.setRole(role);
        user.setSecurityCode(securityCode);

        personal person = new personal();
        person.setUser(user);
        person.setPhoto(new byte[1]);
        user.setPerson(person);
        userService.save(user);

        /* for generate accessNumber by userId */
        user = userService.getRepository().findUserByEmail(user.getEmail());
        person = user.getPerson();
        person.setAccessNumber(formatNum("" + user.getId()));
        user.setPerson(person);
        userService.save(user);

        securityCodeRepository.save(securityCode);
        mailSenderService.sendAuthorizationMail(user, user.getSecurityCode());

    } else {
        this.create(model);
        return "thy/public/signup";

    }
    return "thy/public/mailSent";
}

From source file:com.devnexus.ting.web.controller.RegisterController.java

@RequestMapping(value = "/s/register", method = RequestMethod.POST)
public String validateInitialFormAndPrepareDetailsForm(Model model, @Valid RegisterForm registerForm,
        BindingResult result) {

    Event currentEvent = businessService.getCurrentEvent();
    EventSignup eventSignup = businessService.getEventSignup();
    prepareHeader(currentEvent, model);/*from w ww .  j  a  v a 2  s .  c o m*/
    model.addAttribute("signupRegisterView", new SignupRegisterView(eventSignup));

    int totalTickets = 0;

    for (int i = 0; i < registerForm.getTicketGroupRegistrations().size(); i++) {
        RegisterForm.TicketGroupRegistration ticketReg = registerForm.getTicketGroupRegistrations().get(i);
        TicketGroup ticketGroup = businessService.getTicketGroup(ticketReg.getTicketGroupId());
        ticketReg.setGroup(ticketGroup);
        if (ticketReg.getTicketCount() > 0 && ticketReg.getTicketCount() < ticketGroup.getMinPurchase()) {
            result.addError(new FieldError("registerForm", "ticketGroupRegistrations[" + i + "].ticketCount",
                    "You need to buy more tickets."));
        }

        totalTickets += ticketReg.getTicketCount();

        if (ticketGroup.getCouponCodes() != null && ticketGroup.getCouponCodes().size() > 0
                && !Strings.isNullOrEmpty(ticketReg.getCouponCode())) {
            if (!hasCode(ticketGroup.getCouponCodes(), ticketReg.getCouponCode())) {
                result.addError(new FieldError("registerForm", "ticketGroupRegistrations[" + i + "].couponCode",
                        "Invalid Coupon Code."));
            }
        }
    }

    if (totalTickets == 0) {
        for (int i = 0; i < registerForm.getTicketGroupRegistrations().size(); i++) {
            result.addError(new FieldError("registerForm", "ticketGroupRegistrations[" + i + "].ticketCount",
                    "You must purchase a ticket to continue."));
        }
    }

    if (result.hasErrors()) {
        model.addAttribute("registerForm", registerForm);
        return "register";
    }

    RegistrationDetails registerFormPageTwo = new RegistrationDetails();
    registerFormPageTwo.copyPageOne(registerForm);

    registerFormPageTwo.setFinalCost(getTotal(registerFormPageTwo));

    model.addAttribute("registrationDetails", registerFormPageTwo);

    return "register2";

}