Example usage for org.springframework.validation BindingResult hasFieldErrors

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

Introduction

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

Prototype

boolean hasFieldErrors(String field);

Source Link

Document

Are there any errors associated with the given field?

Usage

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

/**
 * Update user profile info. Check if the user enter valid data and update profile in database.
 * In error case return into the edit profile page and draw the error.
 *
 * @param userDto dto populated by user/*from w w w .  j  a  v  a  2s  .  c  o m*/
 * @param result  binding result which contains the validation result
 * @return in case of errors return back to edit profile page, in another case return to user detalis page
 * @throws NotFoundException   - throws if current logged in user was not found
 * @throws java.io.IOException - throws in case of access errors (if the temporary store fails)
 */
@RequestMapping(value = "/user/edit", method = RequestMethod.POST)
public ModelAndView editProfile(@Valid @ModelAttribute(EDITED_USER) EditUserProfileDto userDto,
        BindingResult result) throws NotFoundException, IOException {

    User user = securityService.getCurrentUser();

    if (result.hasErrors()) {
        //we should show current user avatar (if any)
        //if no file was uploaded, or if there were validation errors on avatar field
        if ((userDto.getAvatar().getSize() == 0) || (result.hasFieldErrors("avatar"))) {
            userDto.setAvatar(
                    new MockMultipartFile("avatar", "", ImageFormats.JPG.getContentType(), user.getAvatar()));
        }
        return new ModelAndView(EDIT_PROFILE, EDITED_USER, userDto);
    }

    User editedUser;
    try {
        editedUser = userService.editUserProfile(userDto.getEmail(), userDto.getFirstName(),
                userDto.getLastName(), userDto.getCurrentUserPassword(), userDto.getNewUserPassword(),
                userDto.getAvatar().getBytes());
    } catch (DuplicateEmailException e) {
        result.rejectValue("email", "validation.duplicateemail");
        return new ModelAndView(EDIT_PROFILE);
    } catch (WrongPasswordException e) {
        result.rejectValue("currentUserPassword", "label.incorrectCurrentPassword",
                "Password does not match to the current password");
        return new ModelAndView(EDIT_PROFILE);
    }
    return new ModelAndView(new StringBuilder().append("redirect:/user/")
            .append(editedUser.getEncodedUsername()).append(".html").toString());
}

From source file:com.denimgroup.threadfix.webapp.controller.EditDefectTrackerController.java

@RequestMapping(value = "/ajax", method = RequestMethod.POST)
public String processSubmitAjax(@PathVariable("defectTrackerId") int defectTrackerId,
        @Valid @ModelAttribute DefectTracker defectTracker, BindingResult result, SessionStatus status,
        Model model) {//from w  ww.j a va2  s  . c o  m

    if (defectTracker != null) {
        defectTracker.setId(defectTrackerId);
    }

    DefectTracker databaseDefectTracker = null;

    if (defectTracker == null || defectTracker.getName() == null
            || defectTracker.getName().trim().equals("") && !result.hasFieldErrors("name")) {
        result.rejectValue("name", null, null, "This field cannot be blank");
    } else {
        databaseDefectTracker = defectTrackerService.loadDefectTracker(defectTracker.getName().trim());
        if (databaseDefectTracker != null && !databaseDefectTracker.getId().equals(defectTracker.getId())) {
            result.rejectValue("name", "errors.nameTaken");
        } else if (!defectTrackerService.checkUrl(defectTracker, result)) {
            if (!result.hasFieldErrors("url")) {
                result.rejectValue("url", "errors.invalid", new String[] { "URL" }, null);
            } else if (result.getFieldError("url").getDefaultMessage() != null && result.getFieldError("url")
                    .getDefaultMessage().equals(AbstractDefectTracker.INVALID_CERTIFICATE)) {
                model.addAttribute("showKeytoolLink", true);
            }
        }
    }

    if (result.hasErrors()) {
        model.addAttribute("contentPage", "config/defecttrackers/forms/editDTForm.jsp");
        return "ajaxFailureHarness";
    } else {
        databaseDefectTracker = defectTrackerService.loadDefectTracker(defectTrackerId);
        if (databaseDefectTracker != null && databaseDefectTracker.getDefectTrackerType() != null
                && defectTracker != null && defectTracker.getDefectTrackerType() != null
                && defectTracker.getDefectTrackerType().getId() != null && !defectTracker.getDefectTrackerType()
                        .getId().equals(databaseDefectTracker.getDefectTrackerType().getId())) {
            defectService.deleteByDefectTrackerId(defectTrackerId);
        }

        defectTrackerService.storeDefectTracker(defectTracker);

        String user = SecurityContextHolder.getContext().getAuthentication().getName();
        if (defectTracker != null) {
            log.debug("The DefectTracker " + defectTracker.getName() + " (id=" + defectTracker.getId()
                    + ") has been edited by user " + user);
            model.addAttribute("successMessage",
                    "Defect Tracker " + defectTracker.getName() + " has been edited successfully.");
        }

        model.addAttribute(defectTrackerService.loadAllDefectTrackers());
        model.addAttribute("defectTracker", new DefectTracker());
        model.addAttribute("editDefectTracker", new DefectTracker());
        model.addAttribute("defectTrackerTypeList", defectTrackerService.loadAllDefectTrackerTypes());

        permissionService.addPermissions(model, null, null, Permission.CAN_MANAGE_DEFECT_TRACKERS);
        model.addAttribute("contentPage", "config/defecttrackers/trackersTable.jsp");
        return "ajaxSuccessHarness";
    }
}

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

@RequestMapping(value = "/{token}", method = RequestMethod.PUT)
public String reset(@PathVariable String token,
        @Validated @ModelAttribute(FORM_MODEL_KEY) PasswordResetForm form, BindingResult errors,
        BlogLanguage blogLanguage, RedirectAttributes redirectAttributes) {
    redirectAttributes.addFlashAttribute(FORM_MODEL_KEY, form);
    redirectAttributes.addFlashAttribute(ERRORS_MODEL_KEY, errors);

    PasswordResetToken passwordResetToken = userService.getPasswordResetToken(token);
    if (passwordResetToken == null) {
        redirectAttributes.addFlashAttribute(INVALID_PASSOWRD_RESET_LINK_ATTR_NAME, true);
        return "redirect:/password-reset";
    }/*from w w  w.ja  va  2  s  .c o m*/
    LocalDateTime now = LocalDateTime.now();
    if (now.isAfter(passwordResetToken.getExpiredAt())) {
        redirectAttributes.addFlashAttribute(INVALID_PASSOWRD_RESET_LINK_ATTR_NAME, true);
        return "redirect:/password-reset";
    }

    if (!errors.hasFieldErrors("newPassword")) {
        if (!ObjectUtils.nullSafeEquals(form.getNewPassword(), form.getNewPasswordRetype())) {
            errors.rejectValue("newPasswordRetype", "MatchRetype");
        }
    }
    if (errors.hasFieldErrors("newPassword*")) {
        return "redirect:/password-reset/{token}";
    }

    PasswordUpdateRequest request = new PasswordUpdateRequest().withUserId(passwordResetToken.getUser().getId())
            .withPassword(form.getNewPassword()).withLanguage(blogLanguage.getLanguage());
    userService.updatePassword(request, passwordResetToken);

    redirectAttributes.getFlashAttributes().clear();
    return "redirect:/login";
}

From source file:com.sf.springsecurityregistration1.web.controllers.AnnouncementDetailsController.java

/**
 * Method used to verify and persist the new announcement.
 *
 * @param status used to remove announcement from the session
 * @param announcement edited/*from  w  ww.  j a v a 2s .  co m*/
 * @param result used to search for errors in form
 * @param request for future code
 * @param errors for future code
 * @return model of next view (search for success, edit for errors)
 */
@RequestMapping(value = "/customer/announcement/create", method = { RequestMethod.POST })
public ModelAndView create(SessionStatus status, @Valid @ModelAttribute Announcements announcement,
        BindingResult result, WebRequest request, Errors errors) {
    String title = changeEncoding(announcement.getTitle(), pageEncoding, dbEncoding);
    announcement.setTitle(title);
    System.out.println("create " + title); // ISO-8859-1
    String header = changeEncoding(announcement.getHeader(), pageEncoding, dbEncoding);
    announcement.setHeader(header);
    String content = changeEncoding(announcement.getContent(), pageEncoding, dbEncoding);
    announcement.setContent(content);
    Announcements registered = null;
    if (!result.hasErrors() && !announcement.getHeader().equals("new")) {
        System.out.println("!result.hasErrors() ");
        registered = createAnnouncement(announcement, result);
    }
    if (registered == null) {
        System.out.println("registered == null");
        //            result.rejectValue("title", "message.title.error");

    }
    if (result.hasErrors()) {
        String titleErrorMessage = result.hasFieldErrors("title")
                ? result.getFieldError("title").getDefaultMessage()
                : "";
        System.out.println("result.hasErrors() " + titleErrorMessage);
        if (!titleErrorMessage.isEmpty()) {
            result.rejectValue("title", "message.title.error",
                    result.getFieldError("title").getDefaultMessage());
        }
        String contentErrorMessage = result.hasFieldErrors("content")
                ? result.getFieldError("content").getDefaultMessage()
                : "";
        if (!contentErrorMessage.isEmpty()) {
            result.rejectValue("content", "message.content.error",
                    result.getFieldError("content").getDefaultMessage());
        }
        ModelAndView model = new ModelAndView("/customer/announcement/create");
        model.addObject("announcements", announcement);
        return model;
        //            return "redirect:/customer/announcement/create";
    } else {
        if (announcement.getHeader().equals("new")) {
            int size = announcement.getNewHeader().length();
            if (size > 25 || 0 == size) {
                result.rejectValue("newHeader", "message.header.error");
                ModelAndView model = new ModelAndView("/customer/announcement/create");
                model.addObject("announcements", announcement);
                return model;
            }
            announcement.setHeader(changeEncoding(announcement.getNewHeader(), pageEncoding, dbEncoding));
            createAnnouncement(announcement, result);
        }
        ModelAndView model = new ModelAndView("/customer/announcement/search");
        //            model.addObject("announcements", announcement);
        model.addObject("announcementSearchCriteria", new AnnouncementSearchCriteria());
        model.addObject("categories", this.announcementService.findAllCategories());
        model.addObject("authors", this.announcementService.findAllAuthors());
        model.addObject("announcementsList",
                this.announcementService.findAnnouncements(new AnnouncementSearchCriteria()));
        status.setComplete();
        return model;
        //            return "redirect:/customer/announcement/search";
    }
}

From source file:com.denimgroup.threadfix.webapp.controller.SystemSettingsController.java

@JsonView(AllViews.FormInfo.class)
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody Object processSubmit(@ModelAttribute DefaultConfiguration defaultConfiguration,
        HttpServletRequest request, BindingResult bindingResult) {

    if (defaultConfiguration.getDeleteUploadedFiles()) {
        try {//from   w  w w  .  j  a va  2 s.  co  m
            scanService.deleteScanFileLocations();
            defaultConfiguration.setDeleteUploadedFiles(false);
        } catch (RestIOException e) {
            return RestResponse
                    .failure("Unable to delete files in 'File Upload Location' directory." + e.getMessage());
        }
    }

    if (defaultConfiguration.getSessionTimeout() != null && defaultConfiguration.getSessionTimeout() > 30) {
        bindingResult.reject("sessionTimeout", null, "30 is the maximum.");
    }

    if (defaultConfiguration.fileUploadLocationExists()) {
        checkingFolder(defaultConfiguration, bindingResult);
    }

    // This was added because Spring autobinding was not saving the export fields properly
    List<CSVExportField> exportFields = list();
    Map<String, String[]> params = request.getParameterMap();
    int index = 0;

    while (index != -1) {
        String key = "csvExportFields[" + index + "]";
        String[] enumValue = params.get(key);

        if (enumValue != null) {
            exportFields.add(CSVExportField.valueOf(enumValue[0]));
            index++;
        } else {
            index = -1;
        }
    }

    defaultConfiguration.setCsvExportFields(exportFields);

    Map<String, String> errors = addReportErrors(defaultConfiguration);

    if (bindingResult.hasErrors() || errors.size() > 0) {

        // TODO look into this
        if (bindingResult.hasFieldErrors("proxyPort")) {
            bindingResult.reject("proxyPort", new Object[] {}, "Please enter a valid port number.");
        }

        return FormRestResponse.failure("Unable save System Settings. Try again.", bindingResult, errors);
    } else {
        defaultConfigService.saveConfiguration(defaultConfiguration);
        return success(defaultConfiguration);
    }
}

From source file:alfio.controller.form.PaymentForm.java

public void validate(BindingResult bindingResult, TotalPrice reservationCost, Event event,
        List<TicketFieldConfiguration> fieldConf) {

    List<PaymentProxy> allowedPaymentMethods = event.getAllowedPaymentProxies();

    Optional<PaymentProxy> paymentProxyOptional = Optional.ofNullable(paymentMethod);
    PaymentProxy paymentProxy = paymentProxyOptional.filter(allowedPaymentMethods::contains)
            .orElse(PaymentProxy.STRIPE);
    boolean priceGreaterThanZero = reservationCost.getPriceWithVAT() > 0;
    boolean multiplePaymentMethods = allowedPaymentMethods.size() > 1;
    if (multiplePaymentMethods && priceGreaterThanZero && !paymentProxyOptional.isPresent()) {
        bindingResult.reject(ErrorsCode.STEP_2_MISSING_PAYMENT_METHOD);
    } else if (priceGreaterThanZero
            && (paymentProxy == PaymentProxy.STRIPE && StringUtils.isBlank(stripeToken))) {
        bindingResult.reject(ErrorsCode.STEP_2_MISSING_STRIPE_TOKEN);
    }//  ww  w . ja va  2s  .  c om

    if (Objects.isNull(termAndConditionsAccepted) || !termAndConditionsAccepted) {
        bindingResult.reject(ErrorsCode.STEP_2_TERMS_NOT_ACCEPTED);
    }

    email = StringUtils.trim(email);

    fullName = StringUtils.trim(fullName);
    firstName = StringUtils.trim(firstName);
    lastName = StringUtils.trim(lastName);

    billingAddress = StringUtils.trim(billingAddress);

    ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "email", ErrorsCode.STEP_2_EMPTY_EMAIL);
    rejectIfOverLength(bindingResult, "email", ErrorsCode.STEP_2_MAX_LENGTH_EMAIL, email, 255);

    if (event.mustUseFirstAndLastName()) {
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "firstName",
                ErrorsCode.STEP_2_EMPTY_FIRSTNAME);
        rejectIfOverLength(bindingResult, "firstName", ErrorsCode.STEP_2_MAX_LENGTH_FIRSTNAME, fullName, 255);
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "lastName", ErrorsCode.STEP_2_EMPTY_LASTNAME);
        rejectIfOverLength(bindingResult, "lastName", ErrorsCode.STEP_2_MAX_LENGTH_LASTNAME, fullName, 255);
    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "fullName", ErrorsCode.STEP_2_EMPTY_FULLNAME);
        rejectIfOverLength(bindingResult, "fullName", ErrorsCode.STEP_2_MAX_LENGTH_FULLNAME, fullName, 255);
    }

    rejectIfOverLength(bindingResult, "billingAddress", ErrorsCode.STEP_2_MAX_LENGTH_BILLING_ADDRESS,
            billingAddress, 450);

    if (email != null && !email.contains("@") && !bindingResult.hasFieldErrors("email")) {
        bindingResult.rejectValue("email", ErrorsCode.STEP_2_INVALID_EMAIL);
    }

    if (hasPaypalTokens() && !PaypalManager.isValidHMAC(new CustomerName(fullName, firstName, lastName, event),
            email, billingAddress, hmac, event)) {
        bindingResult.reject(ErrorsCode.STEP_2_INVALID_HMAC);
    }

    if (!postponeAssignment) {
        boolean success = Optional.ofNullable(tickets).filter(m -> !m.isEmpty()).map(m -> m.entrySet().stream()
                .map(e -> Validator.validateTicketAssignment(e.getValue(), fieldConf, Optional.empty(), event)))
                .filter(s -> s.allMatch(ValidationResult::isSuccess)).isPresent();
        if (!success) {
            bindingResult.reject(ErrorsCode.STEP_2_MISSING_ATTENDEE_DATA);
        }
    }
}

From source file:com.matrimony.controller.RecoverController.java

@RequestMapping(value = "recover", method = RequestMethod.POST)
public String doStringRecover(HttpServletRequest request, String textField, String process,
        @ModelAttribute("recoverUser") User ruser, BindingResult bindingResult) {
    if ("level1".equals(process)) {
        System.out.println("process " + process);
        User userRecover = UserDAO.findByEmail(textField);
        if (userRecover == null) {
            request.setAttribute("recoverRespCode", 0);
        } else {//from ww w . ja v a  2  s  .c  o  m
            request.setAttribute("recoverRespCode", 1);
            String code = recoverUser(userRecover);
            request.getSession().setAttribute("userRecover", userRecover);
            request.getSession().setAttribute("codeRecover", code);
        }
    } else if ("level2".equals(process) && null != request.getSession().getAttribute("codeRecover")) {
        System.out.println("process " + process);
        String c = (String) request.getSession().getAttribute("codeRecover");
        if (c.equals(textField)) {
            request.getSession().setAttribute("codeRecover", null);
            request.getSession().setAttribute("recoverSuccess", true);
            request.setAttribute("recoverRespCode", 4);
        } else {
            request.setAttribute("recoverRespCode", 3);
        }
    } else if ("level3".equals(process) && null != request.getSession().getAttribute("recoverSuccess")) {
        if (bindingResult.hasFieldErrors("username") && bindingResult.hasFieldErrors("password")) {
            request.setAttribute("recoverRespCode", 4);
            return "recoverUser";
        } else {
            User userRecover = (User) request.getSession().getAttribute("userRecover");
            userRecover.setSalt(HashUtil.generateSalt(UUID.randomUUID().toString()));
            userRecover.setPassword(HashUtil.hashPassword(ruser.getPassword(), userRecover.getSalt()));
            UserDAO.Update(userRecover);
            return "redirect:";
        }
    }
    return "recoverUser";
}

From source file:de.blizzy.documentr.web.branch.BranchControllerTest.java

@Test
public void saveBranchButExists() throws IOException, GitAPIException {
    when(repoManager.listProjectBranches(PROJECT)).thenReturn(Lists.newArrayList(BRANCH));

    BranchForm branchForm = new BranchForm(PROJECT, BRANCH, "old_branch"); //$NON-NLS-1$
    BindingResult bindingResult = new BeanPropertyBindingResult(branchForm, "branchForm"); //$NON-NLS-1$
    String view = branchController.saveBranch(branchForm, bindingResult, authentication);
    assertEquals("/project/branch/edit", view); //$NON-NLS-1$
    assertTrue(bindingResult.hasErrors());
    assertTrue(bindingResult.hasFieldErrors("name")); //$NON-NLS-1$
}

From source file:de.blizzy.documentr.web.page.PageControllerTest.java

@Test
public void savePageButNonexistentBranch() throws IOException {
    when(repoManager.listProjectBranches(PROJECT)).thenReturn(Collections.singletonList(BRANCH));
    PageForm pageForm = new PageForm(PROJECT, "nonexistent", PAGE_PATH, PARENT_PAGE, "title", "text", null, //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
            null, ArrayUtils.EMPTY_STRING_ARRAY);
    BindingResult bindingResult = new BeanPropertyBindingResult(pageForm, "pageForm"); //$NON-NLS-1$

    String view = pageController.savePage(pageForm, bindingResult, model, authenticatedAuthentication);
    assertEquals("/project/branch/page/edit", view); //$NON-NLS-1$
    assertTrue(bindingResult.hasErrors());
    assertTrue(bindingResult.hasFieldErrors("branchName")); //$NON-NLS-1$
}

From source file:easycare.web.user.UserController.java

@PreAuthorize("hasAnyAuthority('CREATE_RESMED_USERS', 'CREATE_ORG_USERS')")
@RequestMapping(value = REQUEST_MAPPING_FOR_NEW_USER_CREATION, method = RequestMethod.POST)
public ModelAndView createUser(HttpServletRequest request,
        @ModelAttribute(USER_FORM) @Valid NewUserForm newUserForm, BindingResult result) {
    if (!isProvidedDataValidToProceedUserCreation(newUserForm, result)) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("displayContactInformation", result.hasFieldErrors("contactInformation.*"));
        modelAndView.addObject("displayIdentification", result.hasFieldErrors("licenseNumber"));
        return showNewUserForm(request, modelAndView, newUserForm);
    }//  w  w w. j  a va2s .  c  o m

    User newUser = newUserForm.createUser(securityService, roleService, clock.getCurrentLocalDate());

    try {
        if (securityService.hasCurrentUserGotAuthority(AuthorityEnum.CAN_AUTHENTICATE_AGAINST_IDS)) {
            newUser = userService.createUserWithIdsCertificate(newUser);
        } else if (newUserForm.isPasswordMethodAuto()) {
            newUser = userService.createUserWithEmailActivationToken(newUser);
        } else {
            newUser = userService.createUserWithManualPassword(newUser);
        }
    } catch (IdsServiceException e) {
        log.error("Unable to create user", e);
        ModelAndView modelAndView = new ModelAndView(NEW_USER_FORM);
        modelAndView.addObject("message", messageSource.getMessage(NEW_USER_CREATION_IDS_ERROR_MESSAGE));
        return modelAndView;
    }

    fireCreateSuccessEvent(newUserForm);
    flashScope.addMessage(NEW_USER_CREATION_SUCCESS_MESSAGE);

    String redirect;
    if (securityService.hasCurrentUserGotAuthority(AuthorityEnum.CAN_AUTHENTICATE_AGAINST_IDS)) {
        idsControllerSupport
                .addCertificateRetrievalDetailsToFlashScope(newUser.getCertificateRetrievalPassword());
        redirect = String.format(REDIRECT_TO_IDS_CERT_DETAILS, newUser.getId());
    } else {
        String searchAndPaginationParameters = getQueryStringWithPageNumberFromSession(request,
                SESSION_KEY_PREFIX);
        removeQueryStringAndPageNumberFromSession(request, SESSION_KEY_PREFIX);

        redirect = REDIRECT_TO_USERS + searchAndPaginationParameters;
    }

    return new ModelAndView(redirect);
}