List of usage examples for org.springframework.validation BindingResult getErrorCount
int getErrorCount();
From source file:fragment.web.BillingControllerTest.java
@Test public void testShowRecordDeposit() 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 ww . ja va 2 s. c om request.setAttribute("isSurrogatedTenant", Boolean.TRUE); request.setAttribute("effectiveTenant", tenant); controller.showRecordDeposit(tenant.getParam(), tenant, map, request); Assert.assertTrue(map.containsAttribute("isPayAsYouGoChosen")); 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()); Assert.assertEquals(map.get("show_deposit_record"), true); Assert.assertNotNull(map.get("depositRecord")); }
From source file:net.nicholaswilliams.java.teamcity.plugin.buildNumber.TestSharedBuildNumberController.java
@Test public void testDoHandleAddBuildNumberPost01() throws IOException, ServletException { this.setUpSecurity(); expect(this.request.getParameter("action")).andReturn("add"); expect(this.request.getMethod()).andReturn("POST"); expect(this.request.getParameter("name")).andReturn("help"); expect(this.request.getParameter("description")).andReturn(""); expect(this.request.getParameter("format")).andReturn("{0"); expect(this.request.getParameter("dateFormat")).andReturn("Ym"); expect(this.request.getParameter("counter")).andReturn("15.1"); 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 ww w .j av a2 s. c o m*/ assertTrue("The binding result should have errors.", result.hasErrors()); assertEquals("The binding result should have 3 errors.", 3, result.getErrorCount()); List<FieldError> errors = result.getFieldErrors(); assertNotNull("The list of errors should not be null.", errors); assertEquals("The list length is not correct.", 3, 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.", "name", errors.get(1).getField()); assertEquals("The second error has the wrong message.", "The name must be between 5 and 60 characters long.", errors.get(1).getDefaultMessage()); assertEquals("The third error is not correct.", "format", errors.get(2).getField()); assertEquals("The third error has the wrong message.", "The build number format must be at least 3 characters long.", errors.get(2).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.", "help", form.getName()); assertEquals("The description is not correct.", "", form.getDescription()); assertEquals("The format is not correct.", "{0", form.getFormat()); assertEquals("The date format is not correct.", "Ym", form.getDateFormat()); assertEquals("The counter is not correct.", 1, form.getCounter()); }
From source file:net.nicholaswilliams.java.teamcity.plugin.buildNumber.TestSharedBuildNumberController.java
@Test public void testDoHandleEditBuildNumberPost03() throws IOException, ServletException { this.setUpSecurity(); SharedBuildNumber originalNumber = new SharedBuildNumber(26); expect(this.request.getParameter("action")).andReturn("edit"); expect(this.request.getMethod()).andReturn("POST"); expect(this.request.getParameter("id")).andReturn("26"); expect(this.service.getSharedBuildNumber(26)).andReturn(originalNumber); 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/editBuildNumber.jsp", modelAndView.getViewName()); Map<String, Object> model = modelAndView.getModel(); assertNotNull("The model should not be null.", model); assertEquals("sbnParameterPrefix is not correct.", BuildNumberPropertiesProvider.PARAMETER_PREFIX, model.get("sbnParameterPrefix")); 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 . jav a 2 s. c o 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()); }
From source file:net.nicholaswilliams.java.teamcity.plugin.buildNumber.TestSharedBuildNumberController.java
@Test public void testDoHandleEditBuildNumberPost02() throws IOException, ServletException { this.setUpSecurity(); SharedBuildNumber originalNumber = new SharedBuildNumber(37); expect(this.request.getParameter("action")).andReturn("edit"); expect(this.request.getMethod()).andReturn("POST"); expect(this.request.getParameter("id")).andReturn("37"); expect(this.service.getSharedBuildNumber(37)).andReturn(originalNumber); expect(this.request.getParameter("name")).andReturn("help"); expect(this.request.getParameter("description")).andReturn(""); expect(this.request.getParameter("format")).andReturn("{0"); expect(this.request.getParameter("dateFormat")).andReturn("Ym"); expect(this.request.getParameter("counter")).andReturn("15.1"); 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/editBuildNumber.jsp", modelAndView.getViewName()); Map<String, Object> model = modelAndView.getModel(); assertNotNull("The model should not be null.", model); assertEquals("sbnParameterPrefix is not correct.", BuildNumberPropertiesProvider.PARAMETER_PREFIX, model.get("sbnParameterPrefix")); 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());// ww w. j av a2 s . c o m assertTrue("The binding result should have errors.", result.hasErrors()); assertEquals("The binding result should have 3 errors.", 3, result.getErrorCount()); List<FieldError> errors = result.getFieldErrors(); assertNotNull("The list of errors should not be null.", errors); assertEquals("The list length is not correct.", 3, 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.", "name", errors.get(1).getField()); assertEquals("The second error has the wrong message.", "The name must be between 5 and 60 characters long.", errors.get(1).getDefaultMessage()); assertEquals("The third error is not correct.", "format", errors.get(2).getField()); assertEquals("The third error has the wrong message.", "The build number format must be at least 3 characters long.", errors.get(2).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.", "help", form.getName()); assertEquals("The description is not correct.", "", form.getDescription()); assertEquals("The format is not correct.", "{0", form.getFormat()); assertEquals("The date format is not correct.", "Ym", form.getDateFormat()); assertEquals("The counter is not correct.", 1, form.getCounter()); }
From source file:au.org.ala.biocache.web.OccurrenceController.java
@RequestMapping(value = "/occurrences/index/download*", method = RequestMethod.GET) public String occurrenceIndexDownload(@Valid DownloadRequestParams requestParams, BindingResult result, @RequestParam(value = "apiKey", required = false) String apiKey, @RequestParam(value = "ip", required = false) String ip, Model model, HttpServletResponse response, HttpServletRequest request) throws Exception { if (result.hasErrors()) { logger.info("validation failed " + result.getErrorCount() + " checks"); logger.debug(result.toString()); model.addAttribute("errorMessage", getValidationErrorMessage(result)); //response.setStatus(response.SC_INTERNAL_SERVER_ERROR); return VALIDATION_ERROR;//result.toString(); }// w ww .j a va2 s .c o m ip = ip == null ? getIPAddress(request) : ip; ServletOutputStream out = response.getOutputStream(); //search params must have a query or formatted query for the download to work if (requestParams.getQ().isEmpty() && requestParams.getFormattedQuery().isEmpty()) { return null; } if (apiKey != null) { occurrenceSensitiveDownload(requestParams, apiKey, ip, true, response, request); return null; } try { downloadService.writeQueryToStream(requestParams, response, ip, out, false, true); } catch (Exception e) { logger.error(e.getMessage(), e); } return null; }
From source file:au.org.ala.biocache.web.OccurrenceController.java
@RequestMapping(value = "/occurrences/download/batchFile", method = RequestMethod.GET) public String batchDownload(HttpServletRequest request, @Valid final DownloadRequestParams params, BindingResult result, @RequestParam(value = "file", required = true) String filepath, @RequestParam(value = "directory", required = true, defaultValue = "/data/biocache-exports") final String directory, @RequestParam(value = "ip", required = false) String ip, Model model) throws Exception { if (result.hasErrors()) { logger.info("validation failed " + result.getErrorCount() + " checks"); logger.debug(result.toString()); model.addAttribute("errorMessage", getValidationErrorMessage(result)); //response.setStatus(response.SC_INTERNAL_SERVER_ERROR); return VALIDATION_ERROR;//result.toString(); }//from w ww .j a va 2s .com final File file = new File(filepath); final SpeciesLookupService mySpeciesLookupService = this.speciesLookupService; ip = ip == null ? getIPAddress(request) : ip; final DownloadDetailsDTO dd = downloadService.registerDownload(params, ip, DownloadType.RECORDS_INDEX); if (file.exists()) { Thread t = new Thread() { @Override public void run() { try { //start a thread CSVReader reader = new CSVReader(new FileReader(file)); String[] row = reader.readNext(); while (row != null) { //get an lsid for the name String lsid = mySpeciesLookupService.getGuidForName(row[0]); if (lsid != null) { try { //download records for this row String outputFilePath = directory + File.separatorChar + row[0].replace(" ", "_") + ".txt"; String citationFilePath = directory + File.separatorChar + row[0].replace(" ", "_") + "_citations.txt"; logger.debug( "Outputting results to:" + outputFilePath + ", with LSID: " + lsid); FileOutputStream output = new FileOutputStream(outputFilePath); params.setQ("lsid:\"" + lsid + "\""); Map<String, Integer> uidStats = searchDAO.writeResultsFromIndexToStream(params, output, false, dd, false); FileOutputStream citationOutput = new FileOutputStream(citationFilePath); downloadService.getCitations(uidStats, citationOutput, params.getSep(), params.getEsc()); citationOutput.flush(); citationOutput.close(); output.flush(); output.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } else { logger.error("Unable to match name: " + row[0]); } row = reader.readNext(); } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { downloadService.unregisterDownload(dd); } } }; t.start(); } return null; }
From source file:au.org.ala.biocache.web.OccurrenceController.java
/** * Occurrence search page uses SOLR JSON to display results * * Please NOTE that the q and fq provided to this URL should be obtained * from SearchResultDTO.urlParameters//from w ww . j a va 2 s . c o m * * @return * @throws Exception */ @RequestMapping(value = "/occurrences/download*", method = RequestMethod.GET) public String occurrenceDownload(@Valid DownloadRequestParams requestParams, BindingResult result, @RequestParam(value = "ip", required = false) String ip, @RequestParam(value = "apiKey", required = false) String apiKey, Model model, HttpServletResponse response, HttpServletRequest request) throws Exception { //org.springframework.validation.BindException errors = new org.springframework.validation.BindException(requestParams,"requestParams"); //validator.validate(requestParams, errors); //check to see if the DownloadRequestParams are valid if (result.hasErrors()) { logger.info("validation failed " + result.getErrorCount() + " checks"); logger.debug(result.toString()); model.addAttribute("errorMessage", getValidationErrorMessage(result)); //response.setStatus(response.SC_INTERNAL_SERVER_ERROR); return VALIDATION_ERROR;//result.toString(); } ip = ip == null ? getIPAddress(request) : ip;//request.getRemoteAddr():ip; ServletOutputStream out = response.getOutputStream(); //search params must have a query or formatted query for the downlaod to work if (requestParams.getQ().isEmpty() && requestParams.getFormattedQuery().isEmpty()) { return null; } if (apiKey != null) { return occurrenceSensitiveDownload(requestParams, apiKey, ip, false, response, request); } try { downloadService.writeQueryToStream(requestParams, response, ip, out, false, false); } catch (Exception e) { logger.error(e.getMessage(), e); } return null; }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractUsersController.java
/** * @param form//from ww w. j a v a 2 s .c o m * @param result * @param map * @param status * @return */ @RequestMapping(value = { "/{userParam}/myprofile" }, method = RequestMethod.POST) public String edit(@PathVariable String userParam, @Valid @ModelAttribute("user") UserForm form, BindingResult result, HttpServletRequest request, ModelMap map, SessionStatus status) { logger.debug("###Entering in edit(form,result,map,status) method @POST"); com.citrix.cpbm.access.User user = form.getUser(); MyProfileValidator validator = new MyProfileValidator(); validator.validate(form, result); if (result.hasErrors() && !(result.getErrorCount() == 1 && result.getAllErrors().get(0).getCode().equals("Size") && form.getUser().getUsername().equals("root"))) { displayErrors(result); // TODO to return the edit page with errors return "redirect:/portal/users/" + userParam + "/myprofile"; } User logedInUser = this.getCurrentUser(); if (isEmailBlacklisted(user.getEmail().toLowerCase())) { logger.info("Email Id : " + form.getUser().getEmail() + " rejected because it is not on the whitelist or part of the blacklist. Kindly contact support"); result.rejectValue("user.email", "signup.emaildomain.blacklist.error"); return edit(null, user.getObject().getUuid(), request, map); } if (form.getClearPassword() != null && !form.getClearPassword().isEmpty()) { // password reset if (form.getOldPassword() == null) { result.addError(new FieldError(result.getObjectName(), "oldPassword", null, false, new String[] { "errors.password.required" }, null, null)); } else if (!user.getObject().authenticate(form.getOldPassword())) { result.addError(new FieldError(result.getObjectName(), "oldPassword", null, false, new String[] { "errors.password.invalid" }, null, null)); } else { user.getObject().setClearPassword(form.getClearPassword()); } } com.citrix.cpbm.access.User userClone = form.getUserClone(); // TODO need to do Validation(Once fix this then remove @Ignore annotation against testUpdateUserFail from Test // Suit. form.setPhone(form.getPhone().replaceAll(PHONE_NUMBER_REGEX, "")); // removing all characters from phone number String oldPhone = userClone.getPhoneWithoutIsdCode() != null ? userClone.getPhoneWithoutIsdCode() : ""; boolean phoneVerificationEnabled = false; if (!form.getPhone().equals(oldPhone.replaceAll(PHONE_NUMBER_REGEX, "")) || !form.getCountryCode().toString().equals(user.getCountryCode())) { if (connectorManagementService.getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION) != null && ((TelephoneVerificationService) connectorManagementService .getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION)).isEnabled()) { phoneVerificationEnabled = true; } if (phoneVerificationEnabled && !userService.hasAuthority(logedInUser, "ROLE_ACCOUNT_CRUD")) { String generatedPhoneVerificationPin = (String) request.getSession() .getAttribute("phoneVerificationPin"); String actualPhoneNumber = (String) request.getSession().getAttribute("phoneNumber"); if (form.getUserEnteredPhoneVerificationPin() == null || !form.getUserEnteredPhoneVerificationPin().equals(generatedPhoneVerificationPin) || !areDigitsInPhoneNosEqual(form.getPhone(), actualPhoneNumber)) { map.addAttribute("userEditError", "phoneVerfication.error"); result.rejectValue("phone", "phoneVerfication.error"); parseResult(result, map); return edit(null, user.getObject().getUuid(), request, map); } } } String phoneNo = form.getCountryCode().replaceAll(PHONE_NUMBER_REGEX, "") + COUNTRY_CODE_TO_PHONE_NUMBER_SEPERATOR + form.getPhone().replaceAll(PHONE_NUMBER_REGEX, ""); // Set the phone number if (!phoneVerificationEnabled && StringUtils.isEmpty(form.getPhone())) { user.setPhone(null); } else { user.setPhone(phoneNo); } if ((user.getObject().getTenant().getState() == State.ACTIVE || user.getObject().getTenant().getState() == State.LOCKED || user.getObject().getTenant().getState() == State.SUSPENDED) && !user.getEmail().equals(userClone.getEmail())) { userAlertPreferencesService.createUserAlertPreference(user.getObject(), user.getEmail(), AlertType.USER_EMAIL); // set email so that it wont be updated in users table and other places user.setEmail(userClone.getEmail()); user.setEmailVerified(true); } userService.update(user, result); form.setUser(user); map.addAttribute("user", form); setPage(map, Page.USER_PERSONAL_PROFILE); status.setComplete(); logger.debug("###Exiting edit(form,result,map,status) method @POST"); map.clear(); return "redirect:/portal/users/" + user.getObject().getParam() + "/myprofile"; }
From source file:cdr.forms.FormController.java
@RequestMapping(value = "/{formId}.form", method = RequestMethod.POST) public String processForm(Model model, @PathVariable(value = "formId") String formId, @Valid @ModelAttribute("deposit") Deposit deposit, BindingResult errors, Principal user, SessionStatus sessionStatus,//from ww w. j a v a2 s .c o m @RequestParam(value = "deposit", required = false) String submitDepositAction, HttpServletRequest request, HttpServletResponse response) throws PermissionDeniedException { request.setAttribute("hasSupplementalObjectsStep", formId.equals(SUPPLEMENTAL_OBJECTS_FORM_ID)); // Check that the form submitted by the user matches the one in the session if (!deposit.getFormId().equals(formId)) throw new Error("Form ID in session doesn't match form ID in path"); // this.getAuthorizationHandler().checkPermission(formId, deposit.getForm(), request); // try { request.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e) { LOG.error("Failed to set character encoding", e); } // if (user != null) deposit.getForm().setCurrentUser(user.getName()); // Remove entries set to null, append an entry for elements with append set for (DepositElement element : deposit.getElements()) { Iterator<DepositEntry> iterator = element.getEntries().iterator(); while (iterator.hasNext()) { if (iterator.next() == null) iterator.remove(); } if (element.getAppend() != null) { element.appendEntry(); element.setAppend(null); } } // Check the deposit's files for virus signatures IdentityHashMap<DepositFile, String> signatures = new IdentityHashMap<DepositFile, String>(); for (DepositFile depositFile : deposit.getAllFiles()) scanDepositFile(depositFile, signatures); // If the "submit deposit" button was pressed, run the validator. if (submitDepositAction != null) { Validator validator = new DepositValidator(); validator.validate(deposit, errors); } // If the deposit has validation errors and no virus signatures were detected, display errors if (errors.hasErrors() && signatures.size() == 0) { LOG.debug(errors.getErrorCount() + " errors"); return "form"; } // If the "submit deposit" button was not pressed, render the form again if (submitDepositAction == null) { return "form"; } // Otherwise, display one of the result pages: if we detected a virus signature, display // the virus warning; otherwise, try to submit the deposit and display results. In each // case, we want to do the same cleanup. String view; if (signatures.size() > 0) { model.addAttribute("signatures", signatures); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); view = "virus"; } else { // Redirect for supplemental objects special case if (formId.equals(SUPPLEMENTAL_OBJECTS_FORM_ID)) { return "redirect:/supplemental"; } // We're doing a regular deposit, so call the deposit handler DepositResult result = this.getDepositHandler().deposit(deposit); if (result.getStatus() == Status.FAILED) { LOG.error("deposit failed"); if (getNotificationHandler() != null) getNotificationHandler().notifyError(deposit, result); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); view = "failed"; } else { if (getNotificationHandler() != null) getNotificationHandler().notifyDeposit(deposit, result); view = "success"; } } // Clean up deposit.deleteAllFiles(); sessionStatus.setComplete(); request.setAttribute("formId", formId); request.setAttribute("administratorEmail", getAdministratorEmail()); return view; }