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:com.denimgroup.threadfix.webapp.controller.AddDefectTrackerController.java

@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@Valid @ModelAttribute DefectTracker defectTracker, BindingResult result,
        SessionStatus status, Model model, HttpServletRequest request) {
    if (defectTracker.getName().trim().equals("") && !result.hasFieldErrors("name")) {
        result.rejectValue("name", null, null, "This field cannot be blank");
    }//from   ww  w.j a  va 2  s.c o  m

    if (result.hasErrors()) {
        model.addAttribute("contentPage", "config/defecttrackers/forms/createDTForm.jsp");
        return "ajaxFailureHarness";
    } else {

        DefectTracker databaseDefectTracker = defectTrackerService
                .loadDefectTracker(defectTracker.getName().trim());
        if (databaseDefectTracker != null)
            result.rejectValue("name", "errors.nameTaken");

        if (defectTracker.getDefectTrackerType() == null) {
            result.rejectValue("defectTrackerType.id", "errors.invalid", new String[] { "Defect Tracker Type" },
                    null);

        } else if (defectTrackerService
                .loadDefectTrackerType(defectTracker.getDefectTrackerType().getId()) == null) {
            result.rejectValue("defectTrackerType.id", "errors.invalid",
                    new String[] { defectTracker.getDefectTrackerType().getId().toString() }, null);
        } 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/createDTForm.jsp");
            return "ajaxFailureHarness";
        }

        defectTrackerService.storeDefectTracker(defectTracker);

        String user = SecurityContextHolder.getContext().getAuthentication().getName();
        log.debug(user + " has successfully created a Defect Tracker with the name " + defectTracker.getName()
                + ", the URL " + defectTracker.getUrl() + ", the type "
                + defectTracker.getDefectTrackerType().getName() + ", and the ID " + defectTracker.getId());

        String referrer = request.getHeader("referer");
        if (referrer.contains("configuration/defecttrackers")) {
            model.addAttribute("contentPage", "/configuration/defecttrackers");
            ControllerUtils.addSuccessMessage(request,
                    "Defect Tracker " + defectTracker.getName() + " has been created successfully.");
            return "ajaxRedirectHarness";
        } else {

            Application application = null;
            if (request.getParameter("applicationId") != null) {
                Integer testId = null;
                try {
                    testId = Integer.valueOf((String) request.getParameter("applicationId"));
                    application = applicationService.loadApplication(testId);
                } catch (NumberFormatException e) {
                    log.warn(
                            "Non-numeric value discovered in applicationId field. Someone is trying to tamper with it.");
                }
            }

            model.addAttribute("application", application);
            model.addAttribute("contentPage", "applications/forms/addDTForm.jsp");

            model.addAttribute("newDefectTracker", defectTracker);
            model.addAttribute("defectTrackerList", defectTrackerService.loadAllDefectTrackers());
            model.addAttribute("defectTrackerTypeList", defectTrackerService.loadAllDefectTrackerTypes());
            model.addAttribute("defectTracker", new DefectTracker());
            permissionService.addPermissions(model, null, null, Permission.CAN_MANAGE_DEFECT_TRACKERS);
            return "ajaxSuccessHarness";
        }
    }
}

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

@RequestMapping(method = RequestMethod.POST)
public 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);

    if (errors.hasFieldErrors("email")) {
        return "redirect:/password-reset";
    }//from  w ww  .  j  a v a  2  s.  c  o  m

    PasswordResetTokenCreateRequest request = form.toPasswordResetTokenCreateRequest(blogLanguage);
    PasswordResetToken passwordResetToken;
    try {
        passwordResetToken = userService.createPasswordResetToken(request);
    } catch (EmailNotFoundException e) {
        errors.rejectValue("email", "UsedEmail");
        return "redirect:/password-reset";
    }

    redirectAttributes.getFlashAttributes().clear();
    redirectAttributes.addFlashAttribute("passwordResetToken", passwordResetToken);
    return "redirect:/password-reset?step.token";
}

From source file:com.ccserver.digital.validator.CreditCardApplicationValidatorTest.java

@Test
public void testExistingPhone() {
    // given/*from   ww w .jav a 2  s  .  c o m*/
    CreditCardApplicationDTO creditCardApplicationDTO = new CreditCardApplicationDTO();
    creditCardApplicationDTO.setId(2L);
    creditCardApplicationDTO.setProcessStep(ProcessStep.General);
    PhoneDTO mobile = new PhoneDTO();
    mobile.setCountryCode("+84");
    mobile.setPhoneNumber("090");
    creditCardApplicationDTO.setMobile(mobile);

    CreditCardApplicationDTO creditCardApplicationExisting = new CreditCardApplicationDTO();
    creditCardApplicationExisting.setId(1L);
    creditCardApplicationExisting.setMobile(mobile);
    Mockito.when(creditCardApplicationService.findByMobile(mobile)).thenReturn(creditCardApplicationExisting);

    BindingResult errors = new BeanPropertyBindingResult(creditCardApplicationDTO, "target");
    // when
    creditCardApplicationValidator.validate(creditCardApplicationDTO, errors);
    // then
    Assert.assertTrue(errors.hasFieldErrors("mobile"));
}

From source file:com.autoupdater.server.controllers.FrontEndAPIController.java

/**
 * Handles errors that occurred during remote upload.
 * //w w  w .  ja  v  a2s.  c  o  m
 * @param response
 *            response to send
 * @param result
 *            result of validation
 */
private void handleErrorDuringRemoteUpload(HttpServletResponse response, BindingResult result) {
    int errorCode;
    List<FieldError> errors;

    if (result.hasFieldErrors("username")) {
        errorCode = SC_UNAUTHORIZED;
        errors = result.getFieldErrors("username");
    } else if (result.hasFieldErrors("program")) {
        errorCode = SC_FORBIDDEN;
        errors = result.getFieldErrors("username");
    } else {
        errorCode = SC_BAD_REQUEST;
        errors = result.getFieldErrors();
    }

    StringBuilder builder = new StringBuilder();
    for (FieldError error : errors)
        builder.append(error.getDefaultMessage()).append('\n');
    sendError(response, errorCode, builder.toString());
}

From source file:com.ccserver.digital.validator.CreditCardApplicationValidatorTest.java

@Test
public void validateOtherTabTest() {
    // given/*from  w w  w.  j  a  va  2  s  . c  o  m*/
    CreditCardApplicationDTO creditCardApplicationDTO = new CreditCardApplicationDTO();
    creditCardApplicationDTO.setProcessStep(ProcessStep.Other);
    PhoneDTO mobile = new PhoneDTO();
    mobile.setPhoneNumber("123");
    mobile.setCountryCode("+84");
    creditCardApplicationDTO.setMobile(mobile);
    creditCardApplicationDTO.setPhoneOfReference(mobile);
    BindingResult errors = new BeanPropertyBindingResult(creditCardApplicationDTO, "target");

    // when
    creditCardApplicationValidator.validate(creditCardApplicationDTO, errors);

    // then
    Assert.assertTrue(errors.hasFieldErrors("securityQuestion"));
    Assert.assertTrue(errors.hasFieldErrors("securityAnswer"));
    Assert.assertTrue(errors.hasFieldErrors("referenceName"));
    Assert.assertTrue(errors.hasFieldErrors("relationshipReference"));
    Assert.assertTrue(errors.hasFieldErrors("phoneOfReference"));
    Assert.assertTrue(errors.hasFieldErrors("deliveryCard"));
}

From source file:com.ccserver.digital.validator.CreditCardApplicationValidatorTest.java

@Test
public void validatorEmploymentForBussinessTest() {
    // given//from  w  w w.j  a  v  a2 s  .  c o  m
    CreditCardApplicationDTO creditCardApplicationDTO = new CreditCardApplicationDTO();
    creditCardApplicationDTO.setProcessStep(ProcessStep.Employment);
    creditCardApplicationDTO.setTypeOfEmployement(TypeOfEmployment.Business);
    PhoneDTO mobile = new PhoneDTO();
    creditCardApplicationDTO.setMobile(mobile);

    BindingResult errors = new BeanPropertyBindingResult(creditCardApplicationDTO, "target");

    // when
    creditCardApplicationValidator.validate(creditCardApplicationDTO, errors);

    // then
    Assert.assertTrue(errors.hasErrors());
    Assert.assertTrue(errors.hasFieldErrors("businessStartDate"));
    Assert.assertTrue(errors.hasFieldErrors("monthlyIncome"));
    Assert.assertTrue(errors.hasFieldErrors("licenseNumber"));
    Assert.assertTrue(errors.hasFieldErrors("businessPhone"));
    Assert.assertTrue(errors.hasFieldErrors("businessAddress"));
    Assert.assertTrue(errors.hasFieldErrors("monthlyIncome"));
    Assert.assertTrue(errors.hasFieldErrors("monthlyExpenses"));

}

From source file:com.ccserver.digital.validator.CreditCardApplicationValidatorTest.java

@Test
public void validatorEmploymentForEmploymentTest() {
    // given// www.  ja va 2s.c o m
    CreditCardApplicationDTO creditCardApplicationDTO = new CreditCardApplicationDTO();
    creditCardApplicationDTO.setProcessStep(ProcessStep.Employment);
    creditCardApplicationDTO.setTypeOfEmployement(TypeOfEmployment.Employed);
    PhoneDTO mobile = new PhoneDTO();
    creditCardApplicationDTO.setMobile(mobile);

    BindingResult errors = new BeanPropertyBindingResult(creditCardApplicationDTO, "target");

    // when
    creditCardApplicationValidator.validate(creditCardApplicationDTO, errors);

    // then
    Assert.assertTrue(errors.hasErrors());
    Assert.assertTrue(errors.hasFieldErrors("occupation"));
    Assert.assertTrue(errors.hasFieldErrors("nameOfEmployer"));
    Assert.assertTrue(errors.hasFieldErrors("industry"));
    Assert.assertTrue(errors.hasFieldErrors("employerAddress"));
    Assert.assertTrue(errors.hasFieldErrors("businessTelephone"));
    Assert.assertTrue(errors.hasFieldErrors("monthlyIncome"));
    Assert.assertTrue(errors.hasFieldErrors("monthlyExpenses"));

}

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

@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@PathVariable("defectTrackerId") int defectTrackerId,
        @Valid @ModelAttribute DefectTracker defectTracker, BindingResult result, SessionStatus status,
        Model model) {// w w  w  .java 2 s .c om

    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()) {
        return "config/defecttrackers/form";
    } 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);
        }

        status.setComplete();
        return "redirect:/configuration/defecttrackers/" + defectTrackerId;
    }
}

From source file:es.ucm.fdi.dalgs.academicTerm.web.AcademicTermController.java

/**
 * modify academic POST/*  ww  w .ja v a  2  s  .co m*/
 * 
 * @param id_academic
 * @param newTerm
 * @param bindingResult
 * @param model
 * @param attr
 * @return String
 */
@RequestMapping(value = "/academicTerm/{academicId}/modify.htm", method = RequestMethod.POST)
public String modifyAcademictermPOST(@PathVariable("academicId") Long id_academic,
        @ModelAttribute("academicTerm") @Valid AcademicTerm newTerm, BindingResult bindingResult, Model model,
        RedirectAttributes attr, Locale locale) {

    if (!bindingResult.hasErrors() || bindingResult.hasFieldErrors("degree")) {

        ResultClass<Boolean> resultReturned = serviceAcademicTerm.modifyAcademicTerm(newTerm, id_academic,
                locale);
        if (!resultReturned.hasErrors())
            return "redirect:/academicTerm/page/0.htm?showAll";
        else {
            model.addAttribute("academicTerm", newTerm);

            attr.addFlashAttribute("errors", resultReturned.getErrorsList());

            attr.addFlashAttribute("academicTerm", newTerm);
            return "redirect:/academicTerm/" + id_academic + "/modify.htm";
        }

    } else {

        attr.addFlashAttribute("org.springframework.validation.BindingResult.academicTerm", bindingResult);
        attr.addFlashAttribute("addAcademicTerm", newTerm);
        return "redirect:/academicTerm/" + id_academic + "/modify.htm";

    }

}

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

@Test
public void testEditProfileWithAvatarValidationFailed() throws Exception {
    User user = mock(User.class);
    when(user.getAvatar()).thenReturn(new byte[0]);
    when(securityService.getCurrentUser()).thenReturn(user);
    EditUserProfileDto userDto = mock(EditUserProfileDto.class);
    when(userDto.getAvatar()).thenReturn(
            new MockMultipartFile("avatar", "", ImageFormats.JPG.getContentType(), new byte[] { 1 }));
    BindingResult bindingResult = mock(BindingResult.class);
    when(bindingResult.hasErrors()).thenReturn(true);
    when(bindingResult.hasFieldErrors("avatar")).thenReturn(true);

    ModelAndView mav = controller.editProfile(userDto, bindingResult);

    assertViewName(mav, "editProfile");
    verify(userDto).setAvatar(any(MultipartFile.class));
    verify(userService, never()).editUserProfile(any(String.class), any(String.class), any(String.class),
            any(String.class), any(String.class), Matchers.<byte[]>any());
}