Example usage for org.springframework.validation BindingResult rejectValue

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

Introduction

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

Prototype

void rejectValue(@Nullable String field, String errorCode);

Source Link

Document

Register a field error for the specified field of the current object (respecting the current nested path, if any), using the given error description.

Usage

From source file:org.wallride.web.controller.admin.customfield.CustomFieldBulkDeleteController.java

@RequestMapping
public String delete(@Valid @ModelAttribute("form") CustomFieldBulkDeleteForm form, BindingResult errors,
        String query, AuthorizedUser authorizedUser, RedirectAttributes redirectAttributes) {
    redirectAttributes.addAttribute("query", query);

    if (!form.isConfirmed()) {
        errors.rejectValue("confirmed", "Confirmed");
    }/*from w  w  w  .j a  v  a2s  .c om*/
    if (errors.hasErrors()) {
        logger.debug("Errors: {}", errors);
        return "redirect:/_admin/{language}/customfields/index";
    }

    Collection<CustomField> customFields = null;
    try {
        customFields = customFieldService.bulkDeleteCustomField(form.buildCustomFieldBulkDeleteRequest(),
                errors);
    } catch (ValidationException e) {
        if (errors.hasErrors()) {
            logger.debug("Errors: {}", errors);
            return "redirect:/_admin/{language}/customfields/index";
        }
        throw e;
    }

    List<String> errorMessages = null;
    if (errors.hasErrors()) {
        errorMessages = new ArrayList<>();
        for (ObjectError error : errors.getAllErrors()) {
            errorMessages.add(messageSourceAccessor.getMessage(error));
        }
    }

    redirectAttributes.addFlashAttribute("deletedCustomFields", customFields);
    redirectAttributes.addFlashAttribute("errorMessages", errorMessages);
    return "redirect:/_admin/{language}/customfields/index";
}

From source file:org.wallride.web.controller.admin.signup.SignupController.java

@RequestMapping(method = RequestMethod.POST)
public String save(@Valid @ModelAttribute("form") SignupForm form, BindingResult errors) {
    if (errors.hasErrors()) {
        return "signup/signup";
    }//from   w  w w . j  a  v a  2s.  com

    try {
        signupService.signup(form.toSignupRequest(), User.Role.ADMIN, form.getToken());
    } catch (DuplicateLoginIdException e) {
        errors.rejectValue("loginId", "NotDuplicate");
        return "signup/signup";
    } catch (DuplicateEmailException e) {
        errors.rejectValue("email", "NotDuplicate");
        return "signup/signup";
    }

    return "redirect:/_admin/login";
}

From source file:org.literacyapp.web.content.multimedia.video.VideoCreateController.java

@RequestMapping(method = RequestMethod.POST)
public String handleSubmit(HttpSession session, /*@Valid*/ Video video,
        @RequestParam("bytes") MultipartFile multipartFile, BindingResult result, Model model) {
    logger.info("handleSubmit");

    if (StringUtils.isBlank(video.getTitle())) {
        result.rejectValue("title", "NotNull");
    } else {//w  ww  . j a  v  a 2 s. c om
        Video existingVideo = videoDao.read(video.getTitle(), video.getLocale());
        if (existingVideo != null) {
            result.rejectValue("title", "NonUnique");
        }
    }

    try {
        byte[] bytes = multipartFile.getBytes();
        if (multipartFile.isEmpty() || (bytes == null) || (bytes.length == 0)) {
            result.rejectValue("bytes", "NotNull");
        } else {
            String originalFileName = multipartFile.getOriginalFilename();
            logger.info("originalFileName: " + originalFileName);
            if (originalFileName.toLowerCase().endsWith(".m4v")) {
                video.setVideoFormat(VideoFormat.M4V);
            } else if (originalFileName.toLowerCase().endsWith(".mp4")) {
                video.setVideoFormat(VideoFormat.MP4);
            } else {
                result.rejectValue("bytes", "typeMismatch");
            }

            if (video.getVideoFormat() != null) {
                String contentType = multipartFile.getContentType();
                logger.info("contentType: " + contentType);
                video.setContentType(contentType);

                video.setBytes(bytes);

                // TODO: convert to a default video format?
            }
        }
    } catch (IOException e) {
        logger.error(e);
    }

    if (result.hasErrors()) {
        model.addAttribute("contentLicenses", ContentLicense.values());

        model.addAttribute("literacySkills", LiteracySkill.values());
        model.addAttribute("numeracySkills", NumeracySkill.values());

        return "content/multimedia/video/create";
    } else {
        video.setTitle(video.getTitle().toLowerCase());
        video.setTimeLastUpdate(Calendar.getInstance());
        videoDao.create(video);

        Contributor contributor = (Contributor) session.getAttribute("contributor");

        ContentCreationEvent contentCreationEvent = new ContentCreationEvent();
        contentCreationEvent.setContributor(contributor);
        contentCreationEvent.setContent(video);
        contentCreationEvent.setCalendar(Calendar.getInstance());
        contentCreationEventDao.create(contentCreationEvent);

        if (EnvironmentContextLoaderListener.env == Environment.PROD) {
            String text = URLEncoder
                    .encode(contributor.getFirstName() + " just added a new Video:\n" + " Language: "
                            + video.getLocale().getLanguage() + "\n" + " Title: \"" + video.getTitle()
                            + "\"\n" + " Video format: " + video.getVideoFormat() + "\n" + "See ")
                    + "http://literacyapp.org/content/multimedia/video/list";
            String iconUrl = contributor.getImageUrl();
            SlackApiHelper.postMessage(Team.CONTENT_CREATION, text, iconUrl, "http://literacyapp.org/video/"
                    + video.getId() + "." + video.getVideoFormat().toString().toLowerCase());
        }

        return "redirect:/content/multimedia/video/list";
    }
}

From source file:org.literacyapp.web.content.multimedia.video.VideoEditController.java

@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public String handleSubmit(HttpSession session, Video video, @RequestParam("bytes") MultipartFile multipartFile,
        BindingResult result, Model model) {
    logger.info("handleSubmit");

    if (StringUtils.isBlank(video.getTitle())) {
        result.rejectValue("title", "NotNull");
    } else {/*  w  ww  . j  a  v a  2  s .co  m*/
        Video existingVideo = videoDao.read(video.getTitle(), video.getLocale());
        if ((existingVideo != null) && !existingVideo.getId().equals(video.getId())) {
            result.rejectValue("title", "NonUnique");
        }
    }

    try {
        byte[] bytes = multipartFile.getBytes();
        if (multipartFile.isEmpty() || (bytes == null) || (bytes.length == 0)) {
            result.rejectValue("bytes", "NotNull");
        } else {
            String originalFileName = multipartFile.getOriginalFilename();
            logger.info("originalFileName: " + originalFileName);
            if (originalFileName.toLowerCase().endsWith(".m4v")) {
                video.setVideoFormat(VideoFormat.M4V);
            } else if (originalFileName.toLowerCase().endsWith(".mp4")) {
                video.setVideoFormat(VideoFormat.MP4);
            } else {
                result.rejectValue("bytes", "typeMismatch");
            }

            if (video.getVideoFormat() != null) {
                String contentType = multipartFile.getContentType();
                logger.info("contentType: " + contentType);
                video.setContentType(contentType);

                video.setBytes(bytes);

                // TODO: convert to a default video format?
            }
        }
    } catch (IOException e) {
        logger.error(e);
    }

    if (result.hasErrors()) {
        model.addAttribute("video", video);
        model.addAttribute("contentLicenses", ContentLicense.values());
        model.addAttribute("literacySkills", LiteracySkill.values());
        model.addAttribute("numeracySkills", NumeracySkill.values());
        model.addAttribute("contentCreationEvents", contentCreationEventDao.readAll(video));
        return "content/multimedia/video/edit";
    } else {
        video.setTitle(video.getTitle().toLowerCase());
        video.setTimeLastUpdate(Calendar.getInstance());
        video.setRevisionNumber(Integer.MIN_VALUE);
        videoDao.update(video);

        Contributor contributor = (Contributor) session.getAttribute("contributor");

        ContentCreationEvent contentCreationEvent = new ContentCreationEvent();
        contentCreationEvent.setContributor(contributor);
        contentCreationEvent.setContent(video);
        contentCreationEvent.setCalendar(Calendar.getInstance());
        contentCreationEventDao.update(contentCreationEvent);

        if (EnvironmentContextLoaderListener.env == Environment.PROD) {
            String text = URLEncoder
                    .encode(contributor.getFirstName() + " just edited an Video:\n" + " Language: \""
                            + video.getLocale().getLanguage() + "\n" + " Title: \"" + video.getTitle()
                            + "\"\n" + " Video format: " + video.getVideoFormat() + "\n" + "See ")
                    + "http://literacyapp.org/content/multimedia/video/list";
            String iconUrl = contributor.getImageUrl();
            SlackApiHelper.postMessage(Team.CONTENT_CREATION, text, iconUrl, "http://literacyapp.org/video/"
                    + video.getId() + "." + video.getVideoFormat().toString().toLowerCase());
        }

        return "redirect:/content/multimedia/video/list";
    }
}

From source file:org.literacyapp.web.content.multimedia.audio.AudioCreateController.java

@RequestMapping(method = RequestMethod.POST)
public String handleSubmit(HttpSession session, /*@Valid*/ Audio audio,
        @RequestParam("bytes") MultipartFile multipartFile, BindingResult result, Model model) {
    logger.info("handleSubmit");

    if (StringUtils.isBlank(audio.getTranscription())) {
        result.rejectValue("transcription", "NotNull");
    } else {//from w  w w  . j a va 2s  .c  o  m
        Audio existingAudio = audioDao.read(audio.getTranscription(), audio.getLocale());
        if (existingAudio != null) {
            result.rejectValue("transcription", "NonUnique");
        }
    }

    try {
        byte[] bytes = multipartFile.getBytes();
        if (multipartFile.isEmpty() || (bytes == null) || (bytes.length == 0)) {
            result.rejectValue("bytes", "NotNull");
        } else {
            String originalFileName = multipartFile.getOriginalFilename();
            logger.info("originalFileName: " + originalFileName);
            if (originalFileName.toLowerCase().endsWith(".mp3")) {
                audio.setAudioFormat(AudioFormat.MP3);
            } else if (originalFileName.toLowerCase().endsWith(".ogg")) {
                audio.setAudioFormat(AudioFormat.OGG);
            } else if (originalFileName.toLowerCase().endsWith(".wav")) {
                audio.setAudioFormat(AudioFormat.WAV);
            } else {
                result.rejectValue("bytes", "typeMismatch");
            }

            if (audio.getAudioFormat() != null) {
                String contentType = multipartFile.getContentType();
                logger.info("contentType: " + contentType);
                audio.setContentType(contentType);

                audio.setBytes(bytes);

                // TODO: convert to a default audio format?
            }
        }
    } catch (IOException e) {
        logger.error(e);
    }

    if (result.hasErrors()) {
        model.addAttribute("contentLicenses", ContentLicense.values());

        model.addAttribute("literacySkills", LiteracySkill.values());
        model.addAttribute("numeracySkills", NumeracySkill.values());

        return "content/multimedia/audio/create";
    } else {
        audio.setTranscription(audio.getTranscription().toLowerCase());
        audio.setTimeLastUpdate(Calendar.getInstance());
        audioDao.create(audio);

        Contributor contributor = (Contributor) session.getAttribute("contributor");

        ContentCreationEvent contentCreationEvent = new ContentCreationEvent();
        contentCreationEvent.setContributor(contributor);
        contentCreationEvent.setContent(audio);
        contentCreationEvent.setCalendar(Calendar.getInstance());
        contentCreationEventDao.create(contentCreationEvent);

        if (EnvironmentContextLoaderListener.env == Environment.PROD) {
            String text = URLEncoder.encode(contributor.getFirstName() + " just added a new Audio:\n"
                    + " Language: " + audio.getLocale().getLanguage() + "\n" + " Transcription: \""
                    + audio.getTranscription() + "\"\n" + " Audio format: " + audio.getAudioFormat() + "\n"
                    + "See ") + "http://literacyapp.org/content/multimedia/audio/list";
            String iconUrl = contributor.getImageUrl();
            SlackApiHelper.postMessage(Team.CONTENT_CREATION, text, iconUrl, "http://literacyapp.org/audio/"
                    + audio.getId() + "." + audio.getAudioFormat().toString().toLowerCase());
        }

        return "redirect:/content/multimedia/audio/list";
    }
}

From source file:it.jugpadova.controllers.PasswordRecoveryController.java

@RequestMapping(method = RequestMethod.POST)
@Validation(view = FORM_VIEW)//from ww  w.ja  va2s.com
protected ModelAndView send(@ModelAttribute(PASSWORD_RECOVERY_ATTRIBUTE) PasswordRecovery passwordRecovery,
        BindingResult result, HttpServletRequest req, SessionStatus status) throws Exception {

    String email = passwordRecovery.getEmail();
    logger.debug("email: " + email);
    Jugger jugger = juggerBo.searchByEmail(email);
    if (jugger == null) {
        result.rejectValue("email", "juggerNotFoundByEmail");
        return new ModelAndView(FORM_VIEW);
    }
    if (jugger.getUser().isEnabled() == false) {
        result.rejectValue("email", "juggerBlocked");
        return new ModelAndView(FORM_VIEW);
    }
    juggerBo.passwordRecovery(jugger, Utilities.getBaseUrl(req));
    ModelAndView mv = new ModelAndView("redirect:/home/message.html?messageCode=jugger.pwdchng.sentMail");
    Utilities.addMessageArguments(mv, jugger.getEmail());
    status.setComplete();
    return mv;
}

From source file:org.literacyapp.web.content.multimedia.audio.AudioEditController.java

@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public String handleSubmit(HttpSession session, Audio audio, @RequestParam("bytes") MultipartFile multipartFile,
        BindingResult result, Model model) {
    logger.info("handleSubmit");

    if (StringUtils.isBlank(audio.getTranscription())) {
        result.rejectValue("transcription", "NotNull");
    } else {//from ww  w.  j a  v  a  2  s.co  m
        Audio existingAudio = audioDao.read(audio.getTranscription(), audio.getLocale());
        if ((existingAudio != null) && !existingAudio.getId().equals(audio.getId())) {
            result.rejectValue("transcription", "NonUnique");
        }
    }

    try {
        byte[] bytes = multipartFile.getBytes();
        if (multipartFile.isEmpty() || (bytes == null) || (bytes.length == 0)) {
            result.rejectValue("bytes", "NotNull");
        } else {
            String originalFileName = multipartFile.getOriginalFilename();
            logger.info("originalFileName: " + originalFileName);
            if (originalFileName.toLowerCase().endsWith(".mp3")) {
                audio.setAudioFormat(AudioFormat.MP3);
            } else if (originalFileName.toLowerCase().endsWith(".ogg")) {
                audio.setAudioFormat(AudioFormat.OGG);
            } else if (originalFileName.toLowerCase().endsWith(".wav")) {
                audio.setAudioFormat(AudioFormat.WAV);
            } else {
                result.rejectValue("bytes", "typeMismatch");
            }

            if (audio.getAudioFormat() != null) {
                String contentType = multipartFile.getContentType();
                logger.info("contentType: " + contentType);
                audio.setContentType(contentType);

                audio.setBytes(bytes);

                // TODO: convert to a default audio format?
            }
        }
    } catch (IOException e) {
        logger.error(e);
    }

    if (result.hasErrors()) {
        model.addAttribute("audio", audio);
        model.addAttribute("contentLicenses", ContentLicense.values());
        model.addAttribute("literacySkills", LiteracySkill.values());
        model.addAttribute("numeracySkills", NumeracySkill.values());
        model.addAttribute("contentCreationEvents", contentCreationEventDao.readAll(audio));
        return "content/multimedia/audio/edit";
    } else {
        audio.setTranscription(audio.getTranscription().toLowerCase());
        audio.setTimeLastUpdate(Calendar.getInstance());
        audio.setRevisionNumber(Integer.MIN_VALUE);
        audioDao.update(audio);

        Contributor contributor = (Contributor) session.getAttribute("contributor");

        ContentCreationEvent contentCreationEvent = new ContentCreationEvent();
        contentCreationEvent.setContributor(contributor);
        contentCreationEvent.setContent(audio);
        contentCreationEvent.setCalendar(Calendar.getInstance());
        contentCreationEventDao.update(contentCreationEvent);

        if (EnvironmentContextLoaderListener.env == Environment.PROD) {
            String text = URLEncoder.encode(contributor.getFirstName() + " just edited an Audio:\n"
                    + " Language: " + audio.getLocale().getLanguage() + "\n" + " Transcription: \""
                    + audio.getTranscription() + "\"\n" + " Audio format: " + audio.getAudioFormat() + "\n"
                    + "See ") + "http://literacyapp.org/content/multimedia/audio/list";
            String iconUrl = contributor.getImageUrl();
            SlackApiHelper.postMessage(Team.CONTENT_CREATION, text, iconUrl, "http://literacyapp.org/audio/"
                    + audio.getId() + "." + audio.getAudioFormat().toString().toLowerCase());
        }

        return "redirect:/content/multimedia/audio/list";
    }
}

From source file:org.openmrs.module.adminui.page.controller.myaccount.ChangeSecretQuestionPageController.java

public String post(PageModel model, @BindParams SecretQuestion secretQuestion, BindingResult errors,
        @SpringBean("userService") UserService userService, HttpServletRequest request) {

    if (!secretQuestion.getAnswer().equals(secretQuestion.getConfirmAnswer())) {
        model.put("secretQuestion", secretQuestion);
        errors.rejectValue("confirmAnswer", "adminui.account.answerAndConfirmAnswer.doesNotMatch");
        return "myaccount/changeSecretQuestion";
    }//from  ww w .  j  av a2 s.  c om

    return changeSecretQuestion(secretQuestion, userService, request);
}

From source file:org.homiefund.web.controllers.HomeController.java

@PostMapping("/")
public String submitHome(@Valid @ModelAttribute HomeForm homeForm, BindingResult result, Model model) {
    if (result.hasErrors()) {
        return "home.list";
    } else {//from w  ww . j  a  v a  2  s .  c o  m
        try {
            homeService.create(mapper.map(homeForm, HomeDTO.class));
        } catch (FieldException e) {
            result.rejectValue(e.getField(), e.getMessage());

            return "home.list";
        }
        return "redirect:/auth/home/";
    }
}

From source file:com.senfino.yodo.controller.AccontController.java

private void convertPasswordError(BindingResult bindingResult) {
    for (ObjectError objectError : bindingResult.getGlobalErrors()) {
        String msg = objectError.getDefaultMessage();
        if ("account.password.mismatch.message".equals(msg)) {
            if (bindingResult.hasFieldErrors("password")) {
                bindingResult.rejectValue("password", "error.mismatch");
            }/*from   ww  w . j  av a2s  . c o  m*/
        }
    }
}