List of usage examples for org.springframework.validation BindingResult getFieldError
@Nullable FieldError getFieldError(String field);
From source file:org.terasoluna.tourreservation.app.searchtour.SearchTourFormDateValidatorTest.java
/** * Date parse Error/*from w w w . j a v a 2 s. c o m*/ */ @Test public void testValidate02() { SearchTourFormDateValidator validator = new SearchTourFormDateValidator(); SearchTourForm criteria = new SearchTourForm(); BindingResult result = new DirectFieldBindingResult(criteria, "SearchTourcriteria"); criteria.setDepDay(31); criteria.setDepMonth(2); criteria.setDepYear(2000); // run validator.validate(criteria, result); // assert assertThat(result.hasErrors(), is(true)); FieldError error = result.getFieldError("depYear"); if (error != null) { assertThat(error.getCode(), is("IncorrectDate.inputdate")); assertThat(error.getDefaultMessage(), is("Incorrect date was entered.")); } else { fail("error"); } }
From source file:utils.play.BugWorkaroundForm.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override//from w w w. j av a 2 s . co m public Form<T> bind(final Map<String, String> data, final String... allowedFields) { DataBinder dataBinder = null; Map<String, String> objectData = data; if (rootName == null) { dataBinder = new DataBinder(blankInstance()); } else { dataBinder = new DataBinder(blankInstance(), rootName); objectData = new HashMap<String, String>(); for (String key : data.keySet()) { if (key.startsWith(rootName + ".")) { objectData.put(key.substring(rootName.length() + 1), data.get(key)); } } } if (allowedFields.length > 0) { dataBinder.setAllowedFields(allowedFields); } SpringValidatorAdapter validator = new SpringValidatorAdapter(Validation.getValidator()); dataBinder.setValidator(validator); dataBinder.setConversionService(play.data.format.Formatters.conversion); dataBinder.setAutoGrowNestedPaths(true); dataBinder.bind(new MutablePropertyValues(objectData)); Set<ConstraintViolation<Object>> validationErrors = validator.validate(dataBinder.getTarget()); BindingResult result = dataBinder.getBindingResult(); for (ConstraintViolation<Object> violation : validationErrors) { String field = violation.getPropertyPath().toString(); FieldError fieldError = result.getFieldError(field); if (fieldError == null || !fieldError.isBindingFailure()) { try { result.rejectValue(field, violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(), getArgumentsForConstraint(result.getObjectName(), field, violation.getConstraintDescriptor()), violation.getMessage()); } catch (NotReadablePropertyException ex) { throw new IllegalStateException("JSR-303 validated property '" + field + "' does not have a corresponding accessor for data binding - " + "check your DataBinder's configuration (bean property versus direct field access)", ex); } } } if (result.hasErrors()) { Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>(); for (FieldError error : result.getFieldErrors()) { String key = error.getObjectName() + "." + error.getField(); System.out.println("Error field:" + key); if (key.startsWith("target.") && rootName == null) { key = key.substring(7); } List<Object> arguments = new ArrayList<>(); for (Object arg : error.getArguments()) { if (!(arg instanceof org.springframework.context.support.DefaultMessageSourceResolvable)) { arguments.add(arg); } } if (!errors.containsKey(key)) { errors.put(key, new ArrayList<ValidationError>()); } errors.get(key).add(new ValidationError(key, error.isBindingFailure() ? "error.invalid" : error.getDefaultMessage(), arguments)); } return new Form(rootName, backedType, data, errors, F.Option.None()); } else { Object globalError = null; if (result.getTarget() != null) { try { java.lang.reflect.Method v = result.getTarget().getClass().getMethod("validate"); globalError = v.invoke(result.getTarget()); } catch (NoSuchMethodException e) { } catch (Throwable e) { throw new RuntimeException(e); } } if (globalError != null) { Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>(); if (globalError instanceof String) { errors.put("", new ArrayList<ValidationError>()); errors.get("").add(new ValidationError("", (String) globalError, new ArrayList())); } else if (globalError instanceof List) { for (ValidationError error : (List<ValidationError>) globalError) { List<ValidationError> errorsForKey = errors.get(error.key()); if (errorsForKey == null) { errors.put(error.key(), errorsForKey = new ArrayList<ValidationError>()); } errorsForKey.add(error); } } else if (globalError instanceof Map) { errors = (Map<String, List<ValidationError>>) globalError; } if (result.getTarget() != null) { return new Form(rootName, backedType, data, errors, F.Option.Some((T) result.getTarget())); } else { return new Form(rootName, backedType, data, errors, F.Option.None()); } } return new Form(rootName, backedType, new HashMap<String, String>(data), new HashMap<String, List<ValidationError>>(errors), F.Option.Some((T) result.getTarget())); } }
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 . j a v a2s .c o m*/ 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: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) {// w ww .j av a 2 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: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 www . j a v a 2 s . 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.citrix.cpbm.portal.fragment.controllers.AbstractConnectorController.java
@RequestMapping(value = "/upload_logo", method = RequestMethod.POST) @ResponseBody//from ww w . j a va 2 s . co m public String uploadServiceInstanceLogo(@ModelAttribute("serviceInstanceLogoForm") ServiceInstanceLogoForm form, BindingResult result, HttpServletRequest request, ModelMap map) { logger.debug("### upload service instance logo method starting...(POST)"); String fileSize = checkFileUploadMaxSizeException(request); if (fileSize != null) { result.rejectValue("logo", "error.image.max.upload.size.exceeded"); return messageSource.getMessage(result.getFieldError("logo").getCode(), new Object[] { fileSize }, request.getLocale()); } String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath); if (StringUtils.isNotBlank(rootImageDir)) { ServiceInstance serviceInstance = form.getServiceInstance(); ServiceInstanceLogoFormValidator validator = new ServiceInstanceLogoFormValidator(); validator.validate(form, result); if (result.hasErrors()) { return messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale()); } else { setImagePath(rootImageDir, serviceInstance, form.getLogo()); } return "success"; } else { result.rejectValue("logo", "error.custom.image.upload.dir"); return messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale()); } }
From source file:org.easyj.rest.test.controller.TestEntityControllerTest.java
@Test public void whenPOSTWithWrongParams_returnBadRequest() throws Exception { BindingResult bindingResult; MvcResult result;//from w ww .ja va2 s .com result = mvc.perform(post("/entity").param("id", "1")//@Id should be null on POSTs .param(firstName, firstName).param(lastName, lastName).param(testDateKey, testDate)) .andExpect(status().isBadRequest()) .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue()))) .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit")) .andReturn(); bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME, BindingResult.class); //Validation errors should be bound to result as FieldError assertEquals(false, bindingResult.hasGlobalErrors()); assertEquals(true, bindingResult.hasFieldErrors()); assertEquals(1, bindingResult.getFieldErrorCount()); assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class)); assertThat(bindingResult.getFieldError("id"), notNullValue()); result = mvc.perform(post("/entity") //Not posting firstName a @NotNull param .param(lastName, lastName).param(testDateKey, testDate)).andExpect(status().isBadRequest()) .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue()))) .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit")) .andReturn(); bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME, BindingResult.class); //Validation errors should be bound to result as FieldError assertEquals(false, bindingResult.hasGlobalErrors()); assertEquals(true, bindingResult.hasFieldErrors()); assertEquals(1, bindingResult.getFieldErrorCount()); assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class)); //Missing params should be binded to its own field name assertThat(bindingResult.getFieldError(firstName), notNullValue()); result = mvc.perform(post("/entity").param(firstName, firstName) //Not posting lastName a different @NotNull param .param(testDateKey, testDate)).andExpect(status().isBadRequest()) .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue()))) .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit")) .andReturn(); bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME, BindingResult.class); //Validation errors should be bound to result as FieldError assertEquals(false, bindingResult.hasGlobalErrors()); assertEquals(true, bindingResult.hasFieldErrors()); assertEquals(1, bindingResult.getFieldErrorCount()); assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class)); //Missing params should be binded to its own field name assertThat(bindingResult.getFieldError(lastName), notNullValue()); }
From source file:org.easyj.rest.test.controller.TestEntityControllerTest.java
@Test public void whenPUTWithWrongParams_returnBadRequest() throws Exception { BindingResult bindingResult; MvcResult result;/*from www.j a v a 2s .co m*/ result = mvc.perform(put("/entity/1") //Not posting firstName a @NotNull param .param(lastName, lastName).param(testDateKey, testDate)).andExpect(status().isBadRequest()) .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue()))) .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit")) .andReturn(); bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME, BindingResult.class); //Validation errors should be bound to result as FieldError assertEquals(false, bindingResult.hasGlobalErrors()); assertEquals(true, bindingResult.hasFieldErrors()); assertEquals(1, bindingResult.getFieldErrorCount()); assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class)); //Missing params should be binded to its own field name assertThat(bindingResult.getFieldError(firstName), notNullValue()); result = mvc.perform(put("/entity/1").param(firstName, firstName) //Not posting lastName a different @NotNull param .param(testDateKey, testDate)).andExpect(status().isBadRequest()) .andExpect(model().attribute(BINDING_RESULT_MODEL_NAME, not(nullValue()))) .andExpect(model().attribute("data", not(nullValue()))).andExpect(view().name("entity/edit")) .andReturn(); bindingResult = assertAndReturnModelAttributeOfType(result.getModelAndView(), BINDING_RESULT_MODEL_NAME, BindingResult.class); //Validation errors should be bound to result as FieldError assertEquals(false, bindingResult.hasGlobalErrors()); assertEquals(true, bindingResult.hasFieldErrors()); assertEquals(1, bindingResult.getFieldErrorCount()); assertThat(bindingResult.getTarget(), instanceOf(TestEntity.class)); //Missing params should be binded to its own field name assertThat(bindingResult.getFieldError(lastName), notNullValue()); }
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 www .j ava 2 s .co 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"; } } }