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.literacyapp.web.content.multimedia.image.ImageCreateController.java

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

    if (StringUtils.isBlank(image.getTitle())) {
        result.rejectValue("title", "NotNull");
    } else {/*w w  w  .ja v  a 2  s .  co  m*/
        Image existingImage = imageDao.read(image.getTitle(), image.getLocale());
        if (existingImage != 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(".png")) {
                image.setImageFormat(ImageFormat.PNG);
            } else if (originalFileName.toLowerCase().endsWith(".jpg")
                    || originalFileName.toLowerCase().endsWith(".jpeg")) {
                image.setImageFormat(ImageFormat.JPG);
            } else if (originalFileName.toLowerCase().endsWith(".gif")) {
                image.setImageFormat(ImageFormat.GIF);
            } else {
                result.rejectValue("bytes", "typeMismatch");
            }

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

                image.setBytes(bytes);

                if (image.getImageFormat() != ImageFormat.GIF) {
                    int width = ImageHelper.getWidth(bytes);
                    logger.info("width: " + width + "px");

                    if (width < ImageHelper.MINIMUM_WIDTH) {
                        result.rejectValue("bytes", "image.too.small");
                        image.setBytes(null);
                    } else {
                        if (width > ImageHelper.MINIMUM_WIDTH) {
                            bytes = ImageHelper.scaleImage(bytes, ImageHelper.MINIMUM_WIDTH);
                            image.setBytes(bytes);
                        }
                    }
                }
            }
        }
    } 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/image/create";
    } else {
        image.setTitle(image.getTitle().toLowerCase());
        int[] dominantColor = ImageColorHelper.getDominantColor(image.getBytes());
        image.setDominantColor(
                "rgb(" + dominantColor[0] + "," + dominantColor[1] + "," + dominantColor[2] + ")");
        image.setTimeLastUpdate(Calendar.getInstance());
        imageDao.create(image);

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

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

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

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

From source file:org.literacyapp.web.content.multimedia.image.ImageEditController.java

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

    if (StringUtils.isBlank(image.getTitle())) {
        result.rejectValue("title", "NotNull");
    } else {/*from w w  w.j a v a2s  .c  om*/
        Image existingImage = imageDao.read(image.getTitle(), image.getLocale());
        if ((existingImage != null) && !existingImage.getId().equals(image.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(".png")) {
                image.setImageFormat(ImageFormat.PNG);
            } else if (originalFileName.toLowerCase().endsWith(".jpg")
                    || originalFileName.toLowerCase().endsWith(".jpeg")) {
                image.setImageFormat(ImageFormat.JPG);
            } else if (originalFileName.toLowerCase().endsWith(".gif")) {
                image.setImageFormat(ImageFormat.GIF);
            } else {
                result.rejectValue("bytes", "typeMismatch");
            }

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

                image.setBytes(bytes);

                if (image.getImageFormat() != ImageFormat.GIF) {
                    int width = ImageHelper.getWidth(bytes);
                    logger.info("width: " + width + "px");

                    if (width < ImageHelper.MINIMUM_WIDTH) {
                        result.rejectValue("bytes", "image.too.small");
                        image.setBytes(null);
                    } else {
                        if (width > ImageHelper.MINIMUM_WIDTH) {
                            bytes = ImageHelper.scaleImage(bytes, ImageHelper.MINIMUM_WIDTH);
                            image.setBytes(bytes);
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        logger.error(e);
    }

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

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

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

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

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

From source file:gallery.web.validator.user.UserCmsValidator.java

public BindingResult bindAndValidate(User command, HttpServletRequest request, User old_command) {
    BindingResult err = bindAndValidate(command, request);
    if (!err.hasErrors()) {
        if ((command.getPassword() == null && command.getPassword_repeat() != null)
                || (command.getPassword() != null
                        && !command.getPassword().equals(command.getPassword_repeat()))) {
            err.rejectValue("password_repeat", "password_repeat.different");
        }/*from   w ww. j a v  a2  s .co m*/
        if (old_command == null) {
            if (userService.getRowCount("login", command.getLogin()) > 0) {
                err.rejectValue("login", "exists.login");
            }
            if (userService.getRowCount("email", command.getEmail()) > 0) {
                err.rejectValue("email", "exists.email");
            }
        } else {
            if (command.getPassword() == null || command.getPassword().equals("")) {
                command.setPassword(old_command.getPassword());
            }
            if ((!command.getLogin().equals(old_command.getLogin()))
                    && (userService.getRowCount("login", command.getLogin()) > 0)) {
                err.rejectValue("login", "exists.login");
            }
            if ((!command.getEmail().equals(old_command.getEmail()))
                    && (userService.getRowCount("email", command.getEmail()) > 0)) {
                err.rejectValue("email", "exists.email");
            }
            command.setNewRoles(old_command.getRoles());
        }
    }
    return err;
}

From source file:me.doshou.admin.maintain.notification.web.controller.NotificationTemplateController.java

/**
 * ?true//  www .ja  v  a  2 s  .  c  o  m
 *
 * @param m
 * @param result
 * @return
 */
@Override
protected boolean hasError(NotificationTemplate m, BindingResult result) {
    Assert.notNull(m);

    NotificationTemplate template = getNotificationTemplateService().findByName(m.getName());
    if (template == null || (template.getId().equals(m.getId()) && template.getName().equals(m.getName()))) {
        //success
    } else {
        result.rejectValue("name", "???");
    }

    return result.hasErrors();
}

From source file:gallery.web.validator.user.UserViewValidator.java

public BindingResult bindAndValidate(User command, HttpServletRequest request, User old_command) {
    BindingResult err = bindAndValidate(command, request);
    if (!err.hasErrors()) {
        if ((command.getPassword() == null && command.getPassword_repeat() != null)
                || (command.getPassword() != null
                        && !command.getPassword().equals(command.getPassword_repeat()))) {
            err.rejectValue("password_repeat", "password_repeat.different");
        }/*  w  w  w.  j  a  v a 2 s  .c om*/
        if (old_command == null) {
            //creating new user (insert)
            if (userService.getRowCount("login", command.getLogin()) > 0) {
                err.rejectValue("login", "exists.login");
            }
            if (userService.getRowCount("email", command.getEmail()) > 0) {
                err.rejectValue("email", "exists.email");
            }
            if (!err.hasErrors()) {
                Set<Role> new_roles = new HashSet<Role>(1);
                new_roles.add(new Role("user", command));
                command.setRoles(new_roles);
            }
        } else {
            //user edits his private data (update)
            command.setId(old_command.getId());
            if (!command.getPassword_old().equals(old_command.getPassword())) {
                err.rejectValue("password_old", "password_old.different");
            }
            if (command.getPassword() == null || command.getPassword().equals("")) {
                command.setPassword(old_command.getPassword());
            }
            if ((!command.getLogin().equals(old_command.getLogin()))
                    && (userService.getRowCount("login", command.getLogin()) > 0)) {
                err.rejectValue("login", "exists.login");
            }
            if ((!command.getEmail().equals(old_command.getEmail()))
                    && (userService.getRowCount("email", command.getEmail()) > 0)) {
                err.rejectValue("email", "exists.email");
            }
            if (!err.hasErrors()) {
                command.setRoles(old_command.getRoles());
            }
        }
    }
    return err;
}

From source file:controllers.admin.PostController.java

@PostMapping("/save")
public String processPost(@RequestPart("postImage") MultipartFile postImage,
        @ModelAttribute(ATTRIBUTE_NAME) @Valid Post post, BindingResult bindingResult,
        @CurrentUserAttached User activeUser, RedirectAttributes model) throws IOException, SQLException {

    String url = "redirect:/admin/posts/all";

    if (post.getImage() == null && postImage != null && postImage.isEmpty()) {
        bindingResult.rejectValue("image", "post.image.notnull");
    }/*ww w.ja  v a2  s.  c om*/

    if (bindingResult.hasErrors()) {
        model.addFlashAttribute(BINDING_RESULT_NAME, bindingResult);
        return url;
    }

    if (postImage != null && !postImage.isEmpty()) {
        logger.info("Aadiendo informacin de la imagen");
        FileImage image = new FileImage();
        image.setName(postImage.getName());
        image.setContentType(postImage.getContentType());
        image.setSize(postImage.getSize());
        image.setContent(postImage.getBytes());
        post.setImage(image);
    }

    post.setAuthor(activeUser);
    if (post.getId() == null) {
        postService.create(post);
    } else {
        postService.edit(post);
    }

    List<String> successMessages = new ArrayList();
    successMessages.add(messageSource.getMessage("message.post.save.success", new Object[] { post.getId() },
            Locale.getDefault()));
    model.addFlashAttribute("successFlashMessages", successMessages);
    return url;
}

From source file:cz.muni.fi.editor.webapp.controllers.UserController.java

@RequestMapping(value = "/create/", method = RequestMethod.POST)
public String createSubmit(@Valid @ModelAttribute("userForm") UserFormCreate userForm, BindingResult result) {
    log.fatal(userForm);/*from   w  w  w.j a  v a  2s . c  o  m*/
    // check if passwords are the same
    if (!Objects.equals(userForm.getPassword(), userForm.getPasswordAgain())) {
        userForm.setPassword("");
        userForm.setPasswordAgain("");

        result.rejectValue("passwordAgain", "user.password.nomatch");
    }

    if (result.hasErrors()) {
        return USERS_LIST;
    } else {
        UserDTO user = mapper.map(userForm, UserDTO.class);
        passwordEncoder.hashUserPassword(user);

        try {
            userService.create(user);
        } catch (FieldException ex) {
            log.warn(ex);
            result.rejectValue(ex.getField(), ex.getMessage());

            userForm.setPassword("");
            userForm.setPasswordAgain("");

            return USERS_LIST;
        }

        return REDIRECT;
    }
}

From source file:controllers.admin.SelfUserController.java

@RequestMapping(method = RequestMethod.POST)
public String self(
        // @ModelAttribute will load User from session but also set values from the form post
        @Validated(User.UserUpdate.class) @ModelAttribute(ATTRIBUTE_NAME) User user,
        BindingResult bindingResult, RedirectAttributes redirectAttributes,
        // SessionStatus lets you clear your SessionAttributes
        SessionStatus sessionStatus) {//from   w w  w. j a  v a  2  s.co  m

    logger.info("Usuario a actualizar: " + user.toString());
    if (!bindingResult.hasErrors()) {
        try {
            userService.update(user);
        } catch (UserAlredyExistsException e) {
            bindingResult.rejectValue("email", "user.exists");
        }
    }

    if (bindingResult.hasErrors()) {
        //put the validation errors in Flash session and redirect to self
        redirectAttributes.addFlashAttribute(BINDING_RESULT_NAME, bindingResult);
        return "redirect:/admin/users/self";
    }

    sessionStatus.setComplete(); //remove user from session

    List<String> successMessages = new ArrayList();
    successMessages.add(
            messageSource.getMessage("message.profile.save.success", new Object[] {}, Locale.getDefault()));
    redirectAttributes.addFlashAttribute("successFlashMessages", successMessages);
    return "redirect:/admin/users/self";
}

From source file:org.wallride.web.controller.guest.user.PasswordUpdateController.java

@RequestMapping(method = RequestMethod.PUT)
public String update(@Validated @ModelAttribute(FORM_MODEL_KEY) PasswordUpdateForm form, BindingResult errors,
        AuthorizedUser authorizedUser, RedirectAttributes redirectAttributes) {
    redirectAttributes.addFlashAttribute(FORM_MODEL_KEY, form);
    redirectAttributes.addFlashAttribute(ERRORS_MODEL_KEY, errors);

    if (!errors.hasFieldErrors("newPassword")) {
        if (!ObjectUtils.nullSafeEquals(form.getNewPassword(), form.getNewPasswordRetype())) {
            errors.rejectValue("newPasswordRetype", "MatchRetype");
        }/*from  w  w w .  j av  a 2s .  c  o m*/
    }

    if (!errors.hasErrors()) {
        User user = userService.getUserById(authorizedUser.getId());
        PasswordEncoder passwordEncoder = new StandardPasswordEncoder();
        if (!passwordEncoder.matches(form.getCurrentPassword(), user.getLoginPassword())) {
            errors.rejectValue("currentPassword", "MatchCurrentPassword");
        }
    }

    if (errors.hasErrors()) {
        return "redirect:/settings/password?step.edit";
    }

    PasswordUpdateRequest request = new PasswordUpdateRequest().withUserId(authorizedUser.getId())
            .withPassword(form.getNewPassword());
    userService.updatePassword(request, authorizedUser);

    redirectAttributes.getFlashAttributes().clear();
    redirectAttributes.addFlashAttribute("updatedPassword", true);
    return "redirect:/settings/password";
}

From source file:org.jtalks.common.web.controller.UserController.java

/**
 * Register {@link User} from populated in form {@link RegisterUserDto}.
 *
 * @param userDto {@link RegisterUserDto} populated in form
 * @param result  result of {@link RegisterUserDto} validation
 * @return redirect to / if registration successful or back to "/registration" if failed
 *///from   w w  w . ja  va 2  s  . c  o  m
@RequestMapping(value = "/registration", method = RequestMethod.POST)
public ModelAndView registerUser(@Valid @ModelAttribute("newUser") RegisterUserDto userDto,
        BindingResult result) {
    if (result.hasErrors()) {
        return new ModelAndView(REGISTRATION);
    }

    try {
        userService.registerUser(userDto.createUser());
        return new ModelAndView("redirect:/");
    } catch (DuplicateUserException e) {
        result.rejectValue("username", "validation.duplicateuser");
    } catch (DuplicateEmailException e) {
        result.rejectValue("email", "validation.duplicateemail");
    }
    return new ModelAndView(REGISTRATION);
}