Example usage for org.springframework.validation BindingResult getErrorCount

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

Introduction

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

Prototype

int getErrorCount();

Source Link

Document

Return the total number of errors.

Usage

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

@Test
public void testEditProfileDuplicatedEmail() throws Exception {
    EditUserProfileDto userDto = getEditUserProfileDto();
    BindingResult bindingResult = new BeanPropertyBindingResult(userDto, "editedUser");

    doThrow(new DuplicateEmailException()).when(userService).editUserProfile(userDto.getEmail(),
            userDto.getFirstName(), userDto.getLastName(), userDto.getCurrentUserPassword(),
            userDto.getNewUserPassword(), userDto.getAvatar().getBytes());

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

    assertViewName(mav, "editProfile");
    assertEquals(bindingResult.getErrorCount(), 1, "Result without errors");
    verify(userService).editUserProfile(userDto.getEmail(), userDto.getFirstName(), userDto.getLastName(),
            userDto.getCurrentUserPassword(), userDto.getNewUserPassword(), userDto.getAvatar().getBytes());

    assertContainsError(bindingResult, "email");
}

From source file:com.google.ie.web.controller.ProjectCommentController.java

/**
 * Handles request to add comment on a Project.
 * /*  w  w w .  ja v  a  2  s. c  o  m*/
 * @param projectComment key of the Project on which the comment is to be
 *        added.
 * @param user the User object
 * @throws IOException
 */
@RequestMapping(value = "/postProjectComments", method = RequestMethod.POST)
public void postCommentOnProject(HttpServletRequest request, @ModelAttribute ProjectComment projectComment,
        BindingResult result, Map<String, Object> map, @RequestParam String recaptchaChallengeField,
        @RequestParam String recaptchaResponseField, HttpSession session) throws IOException {
    ViewStatus viewStatus = new ViewStatus();
    Boolean captchaValidation = reCaptchaUtility.verifyCaptcha(request.getRemoteAddr(), recaptchaChallengeField,
            recaptchaResponseField);
    /* call CommentValidator to validate input ProjectComment object */
    getCommentValidator().validate(projectComment, result);
    if (result.hasErrors() || !captchaValidation) {
        logger.warn("Comment object has " + result.getErrorCount() + " validation errors");
        viewStatus.setStatus(WebConstants.ERROR);
        /* Add a message if the captcha validation fails */
        if (!captchaValidation) {
            viewStatus.addMessage(WebConstants.CAPTCHA, WebConstants.CAPTCHA_MISMATCH);
        }
        /* Iterate the errors and add a message for each error */
        for (Iterator<FieldError> iterator = result.getFieldErrors().iterator(); iterator.hasNext();) {
            FieldError fieldError = iterator.next();
            viewStatus.addMessage(fieldError.getField(), fieldError.getDefaultMessage());
            logger.warn("Error found in field: " + fieldError.getField() + " Message :"
                    + fieldError.getDefaultMessage());
        }

    } else {
        User user = (User) session.getAttribute(WebConstants.USER);
        Comment comment = commentService.addComment(projectComment, user);
        if (comment != null) {
            viewStatus.setStatus(WebConstants.SUCCESS);
            viewStatus.addMessage(WebConstants.COMMENTS, WebConstants.COMMENT_SUCCESSFULL);
        } else {
            viewStatus.setStatus(WebConstants.ERROR);
            viewStatus.addMessage(WebConstants.COMMENTS, WebConstants.COMMENT_FAILED);
        }
    }
    map.remove("projectComment");
    map.put(WebConstants.VIEW_STATUS, viewStatus);
}

From source file:eu.scidipes.toolkits.pawebapp.web.ItemsController.java

@RequestMapping(value = { "/edit", "/{formID}/edit", "/new" }, method = RequestMethod.POST)
public String saveItem(@ModelAttribute final SaveAction saveAction, @ModelAttribute final Form form,
        final BindingResult result, final SessionStatus status, final RedirectAttributes redirectAttrs,
        @RequestPart(value = "dataHolder", required = false) final MultipartFile dataFile,
        @MatrixVariable(value = "fn", required = false, pathVar = "datasetName") final String formName) {

    formValidator.validate(form, result);
    if (result.hasErrors()) {
        boolean fixErrors = true;

        final List<FieldError> dataHolderErrors = result.getFieldErrors("dataHolder");

        /*/*  ww  w  .  j av  a  2s  .c o  m*/
         * Only ignore errors under very specific conditions, i.e. when there is a single no-file-supplied error and
         * a current file exists
         */
        if (result.getErrorCount() == 1 && dataHolderErrors != null && dataHolderErrors.size() == 1) {

            final FieldError dataHolderError = dataHolderErrors.get(0);
            if (FormValidator.FILE_REQ_ERR_CODE.equals(dataHolderError.getCode())
                    && !form.getDataHolderMetadata().isEmpty() && form.getDataHolderType() == BYTESTREAM) {
                fixErrors = false;
            }

        }

        if (fixErrors) {
            return "datasets/items/edit";
        }
    }

    /* Ensure that the dataHolder field is not overwritten when its an empty upload (i.e. re-save) */
    if (form.getDataHolderType() == BYTESTREAM && dataFile != null && !dataFile.isEmpty()) {
        LOG.debug("incoming dataFile: {}", dataFile);
        form.getDataHolderMetadata().put(FILE_NAME, dataFile.getOriginalFilename());
        form.getDataHolderMetadata().put(FILE_SIZE, String.valueOf(dataFile.getSize()));
        form.getDataHolderMetadata().put(FILE_MIMETYPE, dataFile.getContentType());
    } else if (form.getDataHolderType() == URI && !StringUtils.isEmpty(form.getDataHolder())) {
        LOG.debug("incoming dataHolder: {}", form.getDataHolder());
        form.getDataHolderMetadata().clear();
    }

    final FormsBundleImpl dataset = datasetRepo.findOne(form.getParentBundle().getDatasetName());

    if (saveAction == ADD_NEW) {
        dataset.addForm(form);
    } else {
        dataset.setForm(form);
    }

    final FormsBundle savedDataset = datasetRepo.save(dataset);
    final Form savedForm = savedDataset.getForms().get(savedDataset.getForms().indexOf(form));

    status.setComplete();
    redirectAttrs.addFlashAttribute("msgKey", "items.edit.messages.savesuccess");

    final String formNameMatrixVar = StringUtils.isEmpty(formName) ? "" : ";fn=" + formName;
    return "redirect:/datasets/" + savedDataset.getDatasetName() + formNameMatrixVar + "/items/"
            + savedForm.getFormID() + "/edit";
}

From source file:com.google.ie.web.controller.CommentController.java

/**
 * Handles request to add comment on Idea.
 * /*  www.ja  v a  2  s  . co  m*/
 * @param ideaComment key of the Idea on which the comment is to be added.
 * @param user the User object
 * @throws IOException
 */
@RequestMapping(value = "/post", method = RequestMethod.POST)
public void postCommentOnIdea(HttpServletRequest request, HttpSession session,
        @ModelAttribute IdeaComment ideaComment, BindingResult result, Map<String, Object> map,
        @RequestParam String recaptchaChallengeField, @RequestParam String recaptchaResponseField)
        throws IOException {

    /*
     * get captcha fields from request call CommentValidator to validate
     * input IdeaComment object
     */
    ViewStatus viewStatus = new ViewStatus();
    Boolean captchaValidation = reCaptchaUtility.verifyCaptcha(request.getRemoteAddr(), recaptchaChallengeField,
            recaptchaResponseField);

    new CommentValidator().validate(ideaComment, result);
    /*
     * check for validation or captcha error and if error occured display
     * the error messages.
     */
    if (result.hasErrors() || !captchaValidation) {
        logger.warn("Comment object has " + result.getErrorCount() + " validation errors");
        viewStatus.setStatus(WebConstants.ERROR);
        if (!captchaValidation) {
            viewStatus.addMessage(WebConstants.CAPTCHA, WebConstants.CAPTCHA_MISMATCH);
        }
        for (Iterator<FieldError> iterator = result.getFieldErrors().iterator(); iterator.hasNext();) {
            FieldError fieldError = iterator.next();
            viewStatus.addMessage(fieldError.getField(), fieldError.getDefaultMessage());
            logger.warn("Error found in field: " + fieldError.getField() + " Message :"
                    + fieldError.getDefaultMessage());
        }

    } else {
        User user = (User) session.getAttribute(WebConstants.USER);
        /* Call comment service to add new comment */
        Comment comment = commentService.addComment(ideaComment, user);

        if (comment != null) {
            viewStatus.setStatus(WebConstants.SUCCESS);
            viewStatus.addMessage(WebConstants.COMMENTS, WebConstants.COMMENT_SUCCESSFULL);
        } else {
            viewStatus.setStatus(WebConstants.ERROR);
            viewStatus.addMessage(WebConstants.COMMENTS, WebConstants.COMMENT_FAILED);
        }
    }
    map.remove("ideaComment");
    map.put(WebConstants.VIEW_STATUS, viewStatus);
}

From source file:fragment.web.BillingControllerTest.java

@Test
public void testRecordDepositPostBindFail() throws Exception {
    Tenant tenant = createTestTenant(accountTypeDAO.getDefaultRegistrationAccountType());
    tenant.setAccountType(accountTypeDAO.getDefaultRegistrationAccountType());
    tenantService.save(tenant);/*w  w  w  .j a va  2  s . c o  m*/
    DepositRecordForm recordForm = new DepositRecordForm();
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    recordForm.setReceivedOn(sdf.format(getDaysFromNow(-3)));
    recordForm.setAmount("1000.00");
    BindingResult result = validate(recordForm);
    Assert.assertEquals("validating that the form has no errors", 0, result.getErrorCount());
    DepositRecordForm returnForm = controller.recordDeposit(tenant.getParam(), recordForm, result, map,
            response);
    Assert.assertNotNull(returnForm);
    Assert.assertNull(tenant.getDeposit());
}

From source file:fragment.web.BillingControllerTest.java

@Test
public void testRecordDeposit2() throws Exception {
    Tenant tenant = createTestTenant(accountTypeDAO.getDefaultRegistrationAccountType());
    DepositRecordForm recordForm = new DepositRecordForm();
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    recordForm.setReceivedOn(sdf.format(getDaysFromNow(-1)));
    recordForm.setAmount("1000.00");
    BindingResult result = validate(recordForm);
    Assert.assertEquals("validating that the form has no errors", 0, result.getErrorCount());
    String returnForm = controller.recordDeposit(tenant.getParam(), tenant, map, request);
    Assert.assertNotNull(returnForm);//from w w  w. j a v  a 2  s . c  o  m
    Assert.assertEquals(200, response.getStatus());
    tenantDAO.flush();
    tenantDAO.clear();
    Tenant found = tenantDAO.find(tenant.getId());
    Assert.assertEquals(tenantService.getDepositRecordByTenant(tenant), found.getDeposit());
}

From source file:fragment.web.BillingControllerTest.java

@Test
public void testRecordDepositPost() throws Exception {
    Tenant tenant = createTestTenant(accountTypeDAO.getDefaultRegistrationAccountType());
    DepositRecordForm recordForm = new DepositRecordForm();
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    recordForm.setReceivedOn(sdf.format(getDaysFromNow(-1)));
    recordForm.setAmount("1000.00");
    BindingResult result = validate(recordForm);
    Assert.assertEquals("validating that the form has no errors", 0, result.getErrorCount());
    DepositRecordForm returnForm = controller.recordDeposit(tenant.getParam(), recordForm, result, map,
            response);//from  w  w w.  ja va  2  s .  com
    Assert.assertNotNull(returnForm);
    Assert.assertEquals(200, response.getStatus());
    tenantDAO.flush();
    tenantDAO.clear();
    Tenant found = tenantDAO.find(tenant.getId());
    Assert.assertEquals(tenantService.getDepositRecordByTenant(tenant), found.getDeposit());
}

From source file:net.nicholaswilliams.java.teamcity.plugin.buildNumber.TestSharedBuildNumberController.java

@Test
public void testDoHandleAddBuildNumberPost02() throws IOException, ServletException {
    this.setUpSecurity();

    expect(this.request.getParameter("action")).andReturn("add");
    expect(this.request.getMethod()).andReturn("POST");
    expect(this.request.getParameter("name")).andReturn("Hello");
    expect(this.request.getParameter("description")).andReturn("This is a description.");
    expect(this.request.getParameter("format")).andReturn("1.0.0.{D}");
    expect(this.request.getParameter("dateFormat")).andReturn("Ym");
    expect(this.request.getParameter("counter")).andReturn("-16");

    replay(this.service, this.request, this.response);

    ModelAndView modelAndView = this.controller.doHandle(this.request, this.response);

    assertNotNull("The model and view should not be null.", modelAndView);
    assertEquals("The view is not correct.", "/plugin/" + testNum + "/jsp/addBuildNumber.jsp",
            modelAndView.getViewName());

    Map<String, Object> model = modelAndView.getModel();
    assertNotNull("The model should not be null.", model);

    Object object = model.get(BindingResult.MODEL_KEY_PREFIX + "sharedBuildNumberForm");
    assertNotNull("The binding result attribute should not be null.", object);
    assertTrue("The binding result attribute should be a binding result object.",
            object instanceof BindingResult);

    BindingResult result = (BindingResult) object;
    assertEquals("The binding result object name is not correct.", "sharedBuildNumberForm",
            result.getObjectName());//from w ww .  ja  va  2 s .co m
    assertTrue("The binding result should have errors.", result.hasErrors());
    assertEquals("The binding result should have 2 errors.", 2, result.getErrorCount());

    List<FieldError> errors = result.getFieldErrors();
    assertNotNull("The list of errors should not be null.", errors);
    assertEquals("The list length is not correct.", 2, errors.size());
    assertEquals("The first error is not correct.", "counter", errors.get(0).getField());
    assertEquals("The first error has the wrong message.", "The counter must be a positive integer.",
            errors.get(0).getDefaultMessage());
    assertEquals("The second error is not correct.", "dateFormat", errors.get(1).getField());
    assertEquals("The second error has the wrong message.",
            "The date format must be at least 3 characters long.", errors.get(1).getDefaultMessage());

    object = model.get("sharedBuildNumberForm");
    assertNotNull("sharedBuildNumberForm should not be null.", object);
    assertTrue("sharedBuildNumberForm should be a SharedBuildNumber.", object instanceof SharedBuildNumber);

    SharedBuildNumber form = (SharedBuildNumber) object;
    assertEquals("The name is not correct.", "Hello", form.getName());
    assertEquals("The description is not correct.", "This is a description.", form.getDescription());
    assertEquals("The format is not correct.", "1.0.0.{D}", form.getFormat());
    assertEquals("The date format is not correct.", "Ym", form.getDateFormat());
    assertEquals("The counter is not correct.", 1, form.getCounter());
}