@RequestMapping(value = "role/update") public ModelAndView updateRole(@ModelAttribute @Valid SysRole sysRole, BindingResult result) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); SysRole checkByName = this.sysRoleUserService.selectByRoleName(sysRole.getRoleName()); if (checkByName != null && checkByName.getRoleId().intValue() != sysRole.getRoleId().intValue()) { FieldError error = new FieldError("sysRole", "roleName", "角色名已存在!"); result.addError(error); } SysRole checkById = this.sysRoleUserService.selectOneRole(sysRole.getRoleId()); if (checkById == null) { FieldError error = new FieldError("sysRole", "roleName", "更新的角色不存在!"); result.addError(error); } if (result.hasErrors()) { List<SysRight> allRights = this.sysRoleUserService.findRights(); RightModuleBuilder builder = RightModuleBuilder.initModules(allRights); map.put("builder", builder); map.put("sysRole", sysRole); return new ModelAndView("sys/sys_role_edit", map); } // update SysRole checkById.setRoleName(sysRole.getRoleName()); checkById.setRoleRightCodes(sysRole.getRoleRightCodes()); this.sysRoleUserService.updateRole(checkById); // map.put("success_msg", "角色修改成功!"); map.put("action", "update"); return new ModelAndView("sys/sys_role_success", map); }
@ResponseBody @RequestMapping(value = "/edit", method = RequestMethod.POST) public ImmutableMap<String, Object> linkEdit(@Valid Link link, BindingResult bindingResult) { if (bindingResult.hasErrors()) { Map<String, Object> errorMessage = Maps.newHashMap(); errorMessage.put("status", 0); List<FieldError> fes = bindingResult.getFieldErrors(); for (FieldError fe : fes) { errorMessage.put(fe.getField(), fe.getDefaultMessage()); } return ImmutableMap.<String, Object>builder().putAll(errorMessage).build(); } if (link.getLinkId() == null || link.getLinkId() == 0) { Link result = linkService.save(link); if (result == null || result.getLinkId() == null || result.getLinkId() == 0) { LOGGER.warn("内容链接失败,链接{}", result); return ImmutableMap.<String, Object>of( "status", "0", "message", getMessage("link.addfailed.message")); } LOGGER.info("内容添加成功,链接ID{}", result.getLinkId()); return ImmutableMap.<String, Object>of( "status", "1", "message", getMessage("link.addsuccess.message")); } try { linkService.save(link); } catch (Exception e) { LOGGER.error("链接修改失败,{}", e); return ImmutableMap.<String, Object>of( "status", "0", "message", getMessage("link.updatefailed.message")); } LOGGER.info("链接添加成功,{}", link); return ImmutableMap.<String, Object>of( "status", "1", "message", getMessage("link.updatesuccess.message")); }
@RequestMapping( value = {"/save"}, method = RequestMethod.POST) public ModelAndView save( @ModelAttribute("backup") @Valid Backup backup, BindingResult result, RedirectAttributes redirectAttributes) { if (result.hasErrors()) return editView(backup); if (!canWrite(backup.getOutputFolder())) { ObjectError error = new ObjectError("backup", "The provided output folder needs write permission"); result.addError(error); return editView(backup); } if (backup.getDatabases() == null || backup.getDatabases().size() == 0) { ObjectError error = new ObjectError("databases", "At least one database needs to be selected"); result.addError(error); return editView(backup); } if (backup.getId() == null) backupService.save(backup); else backupService.update(backup); redirectAttributes.addFlashAttribute("backup", backup); return new ModelAndView("redirect:/backups/list"); }
@Test public void testBindErrorNotWritableWithPrefix() throws Exception { VanillaTarget target = new VanillaTarget(); BindingResult result = bind(target, "spam: bar\n" + "vanilla.value: 123", "vanilla"); assertEquals(0, result.getErrorCount()); assertEquals(123, target.getValue()); }
@RequestMapping(method = RequestMethod.POST) public ModelAndView processFormSubmit( @RequestParam(value = CANCEL_PARAM, required = false) String cancel, @ModelAttribute("savingsProduct") @Valid SavingsProductFormBean savingsProductFormBean, BindingResult result, SessionStatus status) { ModelAndView modelAndView = new ModelAndView("redirect:/previewSavingsProducts.ftl?editFormview=editSavingsProduct"); configurationDto = this.configurationServiceFacade.getAccountingConfiguration(); modelAndView.addObject("GLCodeMode", configurationDto.getGlCodeMode()); if (StringUtils.isNotBlank(cancel)) { modelAndView.setViewName(REDIRECT_TO_ADMIN_SCREEN); status.setComplete(); } else if (result.hasErrors()) { new SavingsProductValidator().validateGroup(savingsProductFormBean, result); modelAndView.setViewName("editSavingsProduct"); } else { new SavingsProductValidator().validateGroup(savingsProductFormBean, result); if (result.hasErrors()) { modelAndView.setViewName("editSavingsProduct"); } } return modelAndView; }
/* * This method will be called on form submission, handling POST request for * updating employee in database. It also validates the user input */ @RequestMapping( value = {"/edit-{ssn}-employee"}, method = RequestMethod.POST) public String updateEmployee( @Valid Employee employee, BindingResult result, ModelMap model, @PathVariable String ssn) { if (result.hasErrors()) { return "registration"; } if (!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())) { FieldError ssnError = new FieldError( "employee", "ssn", messageSource.getMessage( "non.unique.ssn", new String[] {employee.getSsn()}, Locale.getDefault())); result.addError(ssnError); return "registration"; } service.updateEmployee(employee); model.addAttribute("success", "Employee " + employee.getName() + " updated successfully"); return "success"; }
@RequestMapping(method = RequestMethod.POST) public ModelAndView update( @Valid SearchElementEntity elementDefinition, BindingResult bindingResult, HttpServletRequest httpServletRequest, ServerHttpResponse response) { LOGGER.info( "Creating an filed element: " + elementDefinition.getClazz().getSimpleName() + " for preset: " + elementDefinition.getPreset().getSlug()); ModelAndView model = new ModelAndView("admin/SearchElementDefinition/updateForm"); if (bindingResult.hasErrors()) { LOGGER.error("Bindding has error..."); for (ObjectError error : bindingResult.getAllErrors()) { LOGGER.error("Error: " + error.getDefaultMessage()); } response.setStatusCode(HttpStatus.PRECONDITION_FAILED); return model; } try { elementDefinition = repository.save(elementDefinition); } catch (Exception e) { LOGGER.error("Could not save elementDefinition", e); } model.addObject("searchElementDefinition", elementDefinition); return model; }
@RequestMapping(value = "/edit", method = RequestMethod.POST) @ResponseBody public Object editPost( @ModelAttribute("sysAnnouncement") SysAnnouncement sysAnnouncement, BindingResult result, MultipartFile uploadfileAdvise, MultipartFile uploadfileAdviseExtend) throws Exception { if (null == sysAnnouncement.getPubDest()) { SysAnnouncement s = sysAnnouncementDao.findOne(sysAnnouncement.getId()); sysAnnouncement.setPubDest(s.getPubDest()); } if (StringUtils.isBlank(sysAnnouncement.getDescription()) && sysAnnouncement.getPubDest().equals("1")) { result.rejectValue("description", "server", "公告内容不能为空"); return JsonRespWrapper.error(result.getFieldErrors()); } if ("1".equals(sysAnnouncement.getPubDest())) { sysAnnouncement.setTitle(sysAnnouncement.getTitle().split(",")[0]); } if ("3".equals(sysAnnouncement.getPubDest())) { sysAnnouncement.setTitle(sysAnnouncement.getTitle().split(",")[1]); } sysAnnouncement.setEndTime( sysAnnouncement.getEndTime().replaceAll("-", "").replaceAll(" ", "").replaceAll(":", "")); this.sysAnnouncementService.save(sysAnnouncement, uploadfileAdvise, uploadfileAdviseExtend); logUtils.logAdd("编辑公告内容,", "修改成功,公告编号:", +sysAnnouncement.getId()); return JsonRespWrapper.success("操作成功", "/websys/announcement"); }
@RequestMapping(value = "/add", method = RequestMethod.POST) @ResponseBody public Object addPost( @ModelAttribute("sysAnnouncement") SysAnnouncement sysAnnouncement, BindingResult result, MultipartFile uploadfileAdvise, MultipartFile uploadfileAdviseExtend) throws Exception { if (StringUtils.isBlank(sysAnnouncement.getDescription()) && sysAnnouncement.getPubDest().equals("1")) { result.rejectValue("description", "server", "公告内容不能为空"); return JsonRespWrapper.error(result.getFieldErrors()); } if ("1".equals(sysAnnouncement.getPubDest())) { sysAnnouncement.setTitle( sysAnnouncement.getTitle().substring(0, sysAnnouncement.getTitle().length() - 2)); } if ("3".equals(sysAnnouncement.getPubDest())) { sysAnnouncement.setTitle(sysAnnouncement.getTitle().substring(1)); } logUtils.logAdd("添加公告内容", "添加成功"); sysAnnouncement.setEndTime( sysAnnouncement.getEndTime().replaceAll("-", "").replaceAll(" ", "").replaceAll(":", "")); this.sysAnnouncementService.save(sysAnnouncement, uploadfileAdvise, uploadfileAdviseExtend); return JsonRespWrapper.success("操作成功", "/websys/announcement"); }
@RequestMapping(method = RequestMethod.POST) public String update( @PathVariable String language, @Validated @ModelAttribute(FORM_MODEL_KEY) GoogleAnalyticsUpdateForm form, BindingResult errors, @AuthenticationPrincipal AuthorizedUser authorizedUser, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute(FORM_MODEL_KEY, form); redirectAttributes.addFlashAttribute(ERRORS_MODEL_KEY, errors); if (errors.hasErrors()) { return "redirect:/_admin/{language}/analytics/edit?step.edit"; } GoogleAnalyticsUpdateRequest request = new GoogleAnalyticsUpdateRequest(); request.setBlogId(Blog.DEFAULT_ID); request.setTrackingId(form.getTrackingId()); request.setProfileId(form.getProfileId()); request.setCustomDimensionIndex(form.getCustomDimensionIndex()); request.setServiceAccountId(form.getServiceAccountId()); request.setServiceAccountP12File(form.getServiceAccountP12File()); GoogleAnalytics updatedGoogleAnalytics; try { updatedGoogleAnalytics = blogService.updateGoogleAnalytics(request); } catch (GoogleAnalyticsException e) { errors.reject("GoogleAnalytics"); return "redirect:/_admin/{language}/analytics/edit?step.edit"; } redirectAttributes.getFlashAttributes().clear(); redirectAttributes.addFlashAttribute("updatedGoogleAnalytics", updatedGoogleAnalytics); return "redirect:/_admin/{language}/analytics"; }
public static void printResultErrors(BindingResult result) { if (result.hasErrors()) { List<ObjectError> errors = result.getAllErrors(); for (ObjectError error : errors) System.out.println(error.getObjectName() + ", " + error.getDefaultMessage()); } }
/** * méthode pour gérer les problèmes de validation de l'objet resource * * @param exception * @param response * @return */ @ExceptionHandler @ResponseBody public Map<String, Object> handleException(Exception exception, HttpServletResponse response) { LOGGER.error("Exception : ", exception); Map<String, Object> mapErrorMessage = new HashMap<>(); if (exception instanceof MethodArgumentNotValidException) { BindingResult result = ((MethodArgumentNotValidException) exception).getBindingResult(); List<FieldError> listFieldErrors = result.getFieldErrors(); for (FieldError fieldError : listFieldErrors) { mapErrorMessage.put(fieldError.getField(), fieldError.getDefaultMessage()); } response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } if (exception instanceof AccessDeniedException) { mapErrorMessage.put("Error : ", exception.getMessage()); response.setStatus(HttpServletResponse.SC_FORBIDDEN); } else if (exception instanceof ValidationException || exception instanceof HttpMessageNotReadableException || exception instanceof DataAccessException || exception instanceof MongoException || exception instanceof SocketTimeoutException || exception instanceof RuntimeException) { mapErrorMessage.put("Error : ", exception.getMessage()); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } LOGGER.error(mapErrorMessage.toString(), exception); return mapErrorMessage; }
@RequestMapping(value = "/contacts/update", method = RequestMethod.POST) public String createOrUpdateContact( Model model, @ModelAttribute Contact contact, BindingResult result) { if (result.hasErrors()) { model.addAttribute( contact.getId() == null ? ModelAttrs.CONTACT_CREATE.toString() : ModelAttrs.CONTACT_EDIT.toString(), true); // TO CHANGE model.addAttribute(ModelAttrs.HAS_ERRORS.toString(), true); model.addAttribute(ModelAttrs.FIELD_ERRORS.toString(), result.getFieldErrors()); model.addAttribute(ModelAttrs.CONTACT_BEAN.toString(), contact); return ViewData.new_contacts.getViewName(); } System.out.println("contact retrieved: " + contact.getNom()); if (contact.getId() == null) { this.contactsManager.persist(contact); } else { this.contactsManager.merge(contact); } return "redirect:/contacts/list"; }
@RequestMapping(value = "/shift/{shiftId}/edit", method = RequestMethod.POST) public ModelAndView editShift( @PathVariable("shiftId") final Integer shiftId, @Valid @ModelAttribute("shift") Shift shift, BindingResult result) { ModelAndView mav = new ModelAndView(); if (result.hasErrors()) { return new ModelAndView("shift/create", "shift", shift); } Event event = eventService.get(shift.getEvent().getId()); // Set Dates to today shift.setStartTime(convertDateToToday(shift.getStartTime(), event.getDate())); shift.setEndTime(convertDateToToday(shift.getEndTime(), event.getDate())); try { shiftService.edit(shift); } catch (NotValidException e) { LOGGER.warn(e); result.addAllErrors(e.getErrors()); return new ModelAndView("shift/create", "shift", shift); } return new ModelAndView("redirect:/event/" + shift.getEvent().getId() + "/edit"); }
@Override public ModelAndView postEditView( @ModelAttribute("Model") Player model, HttpServletRequest request, BindingResult result) { validator.validate(model, result); if (result.hasErrors()) { return getEditView(model); } // make sure not to overwrite passwordHash, verfied etc. Player player; if (model.getId() != null) { player = playerDAO.findById(model.getId()); } else { Player existingPlayer = playerDAO.findByEmail(model.getEmail()); if (existingPlayer != null) { result.addError(new ObjectError("email", msg.get("EmailAlreadyRegistered"))); return getEditView(model); } player = new Player(); } player.setEmail(model.getEmail()); player.setFirstName(model.getFirstName()); player.setLastName(model.getLastName()); player.setPhone(model.getPhone()); player.setGender(model.getGender()); player.setInitialRanking(model.getInitialRanking()); playerDAO.saveOrUpdate(player); return redirectToIndex(request); }
/** 提交并保存支路信息 */ @ResourceMapping(value = "submitCircuitinfoForm") public Resultmsg onSubmitCircuitinfoForm( @ModelAttribute("circuitinfo") Circuitinfo circuitinfo, BindingResult result, SessionStatus status, ResourceRequest request, ResourceResponse response) { Resultmsg msg = new Resultmsg(); boolean isnew = true; if (request.getParameter("isnew") == null) { msg.setMsg("页面缺少新增或编辑标记 isnew"); } else { isnew = Boolean.valueOf(request.getParameter("isnew")); } new CircuitinfoValidator().validate(circuitinfo, result); if (result.hasErrors()) { logger.error(result); msg.setMsg(result.toString()); } else { try { if (isnew) { circuitinfoService.addCircuitinfo(circuitinfo); } else { circuitinfoService.updateCircuitinfo(circuitinfo); } status.setComplete(); msg.setMsg(circuitinfo.getCircuitId()); msg.setSuccess("true"); } catch (Exception e) { logger.error(e); msg.setMsg(e.getMessage()); } } return msg; }
@Test public void updateBindingResultErrors() { // Given Model model = new ExtendedModelMap(); givenPopulateModel(); Entry entry = entryFactoryForTest.newEntry(); BindingResult bindingResult = mock(BindingResult.class); when(bindingResult.hasErrors()).thenReturn(true); RedirectAttributes redirectAttributes = mock(RedirectAttributes.class); HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); // When String viewName = entryController.update(entry, bindingResult, model, redirectAttributes, httpServletRequest); // Then assertEquals("entry/form", viewName); Map<String, ?> modelMap = model.asMap(); assertEquals(entry, (Entry) modelMap.get("entry")); assertEquals("update", modelMap.get("mode")); assertEquals("/entry/update", modelMap.get("saveAction")); @SuppressWarnings("unchecked") List<EntrytypeListItem> entrytypeListItems = (List<EntrytypeListItem>) modelMap.get("listOfEntrytypeItems"); assertEquals(2, entrytypeListItems.size()); }
@RequestMapping(value = "/register", method = RequestMethod.POST) public String addNewUser( @Valid @ModelAttribute("student") Student student, BindingResult br, Model model) { if (stdao.containsUsername(student.getUsername())) { br.rejectValue("username", "student.username", "This username is taken."); } if (!student.getPassword().equals(student.getConfirmPassword())) { br.rejectValue("confirmPassword", "student.confirmPassword", "Passwords do not match."); } if (!student.getPassword().matches("^(?=.*[0-9])(?=.*[a-z])([a-z0-9_-]+)$")) { br.rejectValue( "password", "student.password", "Password must contain characters and numeric values."); } if (student.getPassword().length() > 20) { br.rejectValue("password", "student.password", "Password must be 20 characters at most."); } if (br.hasErrors()) { return "register"; } student.setDateEnrolled(new Date()); student.setRole("ROLE_STUDENT"); stdao.save(student); model.addAttribute( "message", "Thank you for registering " + student.getFirstName() + " " + student.getLastName() + ".<br/>Please await for an administrator to activate your account."); return "index"; }
/* * This method will be called on form submission, handling POST request for * saving employee in database. It also validates the user input */ @RequestMapping( value = {"/new"}, method = RequestMethod.POST) public String saveEmployee(@Valid Employee employee, BindingResult result, ModelMap model) { if (result.hasErrors()) { return "registration"; } /* * Preferred way to achieve uniqueness of field [ssn] should be * implementing custom @Unique annotation and applying it on field [ssn] * of Model class [Employee]. * * Below mentioned peace of code [if block] is to demonstrate that you * can fill custom errors outside the validation framework as well while * still using internationalized messages. */ if (!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())) { FieldError ssnError = new FieldError( "employee", "ssn", messageSource.getMessage( "non.unique.ssn", new String[] {employee.getSsn()}, Locale.getDefault())); result.addError(ssnError); return "registration"; } employee.setId(service.getNext().intValue()); service.saveEmployee(employee); model.addAttribute("success", "Employee " + employee.getName() + " registered successfully"); return "success"; }
/** * AJAX Called once user is submitting upload form * * @param model * @param file - Uploaded file * @param comment - Comment for uploaded file * @return */ @RequestMapping(method = RequestMethod.POST) public @ResponseBody JsonResponse uploadAction( @Valid @ModelAttribute(value = "image") Image image, @RequestParam(value = "captcha_challenge", required = true) String challenge, @RequestParam(value = "captcha_response", required = true) String response, BindingResult result, HttpServletRequest paramHttpServletRequest) { JsonResponse jsonResponse = new JsonResponse(); String remoteAddr = paramHttpServletRequest.getRemoteAddr(); ReCaptchaResponse reCaptchaResponse = recaptcha.checkAnswer(remoteAddr, challenge, response); if (!reCaptchaResponse.isValid()) { jsonResponse.setCaptchaError( context.getMessage("error.bad.captcha", null, Locale.getDefault())); return jsonResponse; } prepareImage(image); (new ImageValidator()).validate(image, result); if (!result.hasErrors()) { try { image.setBytes(image.getFile().getBytes()); image.setContentType(image.getFile().getContentType()); image = imageService.saveImage(image); jsonResponse.setResponse(paramHttpServletRequest.getRequestURL() + image.getId()); } catch (Exception e) { log.error(e.getMessage()); } } else { for (ObjectError error : result.getAllErrors()) { jsonResponse.appendError(context.getMessage(error.getCode(), null, Locale.getDefault())); } } return jsonResponse; }
protected String createUser( final B2BCustomerForm b2BCustomerForm, final BindingResult bindingResult, final Model model, final RedirectAttributes redirectModel) throws CMSItemNotFoundException { if (bindingResult.hasErrors()) { GlobalMessages.addErrorMessage(model, "form.global.error"); model.addAttribute(b2BCustomerForm); return editUser(b2BCustomerForm.getUid(), model); } final CustomerData b2bCustomerData = new CustomerData(); b2bCustomerData.setTitleCode(b2BCustomerForm.getTitleCode()); b2bCustomerData.setFirstName(b2BCustomerForm.getFirstName()); b2bCustomerData.setLastName(b2BCustomerForm.getLastName()); b2bCustomerData.setEmail(b2BCustomerForm.getEmail()); b2bCustomerData.setDisplayUid(b2BCustomerForm.getEmail()); b2bCustomerData.setUnit( companyB2BCommerceFacade.getUnitForUid(b2BCustomerForm.getParentB2BUnit())); b2bCustomerData.setRoles(b2BCustomerForm.getRoles()); model.addAttribute(b2BCustomerForm); model.addAttribute("titleData", getUserFacade().getTitles()); model.addAttribute("roles", populateRolesCheckBoxes(companyB2BCommerceFacade.getUserGroups())); storeCmsPageInModel(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE)); setUpMetaDataForContentPage( model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE)); final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.getBreadcrumbs(null); breadcrumbs.add( new Breadcrumb( "/my-company/organization-management/", getMessageSource() .getMessage( "text.company.organizationManagement", null, getI18nService().getCurrentLocale()), null)); breadcrumbs.add( new Breadcrumb( "/my-company/organization-management/manage-user", getMessageSource() .getMessage("text.company.manageUsers", null, getI18nService().getCurrentLocale()), null)); model.addAttribute("breadcrumbs", breadcrumbs); try { b2bCommerceUserFacade.updateCustomer(b2bCustomerData); b2bCustomerData.setUid(b2BCustomerForm.getEmail().toLowerCase()); GlobalMessages.addFlashMessage( redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER, "text.confirmation.user.added"); } catch (final DuplicateUidException e) { bindingResult.rejectValue("email", "text.manageuser.error.email.exists.title"); GlobalMessages.addErrorMessage(model, "form.global.error"); model.addAttribute("b2BCustomerForm", b2BCustomerForm); return editUser(b2BCustomerForm.getUid(), model); } return String.format(REDIRECT_TO_USER_DETAILS, urlEncode(b2bCustomerData.getUid())); }
@RequestMapping( value = {"/", "/login"}, method = RequestMethod.POST) public String loginCheck( EmployeeDetails objEmployeeDetails, BindingResult result, ModelMap redirectedModel, HttpSession session) { if (objEmployeeDetails.getEmpLoginName() == null || objEmployeeDetails.getEmpLoginName().isEmpty() || objEmployeeDetails.getEmpPassword() == null || objEmployeeDetails.getEmpPassword().isEmpty()) { result.addError( new FieldError("empLoginName", "empLoginName", "Username or password can not be blank.")); return "login"; } EmployeeDetails objEmpChkLogin = objEmployeeDetailsService.getEmployeeDetailsByUserPassword( objEmployeeDetails.getEmpLoginName(), objEmployeeDetails.getEmpPassword()); if (objEmpChkLogin == null) { result.addError( new FieldError("empLoginName", "empLoginName", "Username or password is wrong.")); } else { session.setAttribute("empDetails", objEmpChkLogin); return "redirect:/home"; } return "login"; }
@Test public void testBindShallowMap() throws Exception { Map<String, Object> target = new LinkedHashMap<String, Object>(); BindingResult result = bind(target, "vanilla.spam: bar\n" + "vanilla.value: 123", "vanilla"); assertEquals(0, result.getErrorCount()); assertEquals("123", target.get("value")); }
@RequestMapping(value = "/update") public @ResponseBody ResponseObject update( @RequestBody @Valid Product product, BindingResult errors) throws Exception { if (errors.hasErrors()) throw new ValidateException(errors.getAllErrors().get(0).getDefaultMessage()); return productService.update(product); }
public CreateJournalEntry( TravelLogDAO dao, Journal journal, BindingResult result, boolean preload, ModelMap map, Logger logger) { // If we're preloading the sample, just skip to the preload method if (preload) { preloadJournal(dao, logger); } else { if (journal.getTitle().length() == 0) { result.reject("title", "Title cannot be blank"); } // check to make sure we don't already have a journal if (dao.getJournals().size() > 0) { result.reject("title", "Journal already exists. Please reload page."); } if (!result.hasErrors()) { dao.saveJournal(journal); } } }
public static void checkBreakfast(Breakfast breakfast, BindingResult result) throws FormException { Date date = breakfast.getDate(); String name = breakfast.getName(); String commentaire = breakfast.getComment(); List<String> errors = new ArrayList<>(); Map<String, FormExceptionFeedBack> feedBacks = new HashMap<>(); if (date == null) { errors.add("La date de l'évènement est obligatoire."); feedBacks.put("Date", FormExceptionFeedBack.ERROR); } if (name == null || name == "") { errors.add("Le nom est obligatoire."); feedBacks.put("Name", FormExceptionFeedBack.ERROR); } if (commentaire == null || commentaire == "") { feedBacks.put("Comment", FormExceptionFeedBack.WARNING); } if (result.hasFieldErrors("name")) { errors.add(result.getFieldError("name").getDefaultMessage()); feedBacks.put("Name", FormExceptionFeedBack.ERROR); } if (result.hasFieldErrors("comment")) { errors.add(result.getFieldError("comment").getDefaultMessage()); feedBacks.put("Comment", FormExceptionFeedBack.ERROR); } if (errors.size() > 0 || result.hasErrors()) throw new FormException("Erreur sauvegarde membre", feedBacks, errors); }
protected void handleResultErrors(BindingResult result) throws EscreeningDataValidationException { if (result.hasErrors()) { ErrorBuilder<EscreeningDataValidationException> errorBuilder = ErrorBuilder.throwing(EscreeningDataValidationException.class); for (ObjectError objectError : result.getAllErrors()) { ErrorMessage errorMessage = new ErrorMessage(); if (objectError instanceof FieldError) { errorMessage.setName(((FieldError) objectError).getField()); } else { errorMessage.setName(objectError.getObjectName()); } errorMessage.setDescription(objectError.getDefaultMessage()); errorBuilder.toUser(errorMessage); } // set admin message and throw error errorBuilder .toAdmin( "BaseDashboardRestController.handleResultErrors: called with " + result.getAllErrors().size() + " errors") .throwIt(); } }
public static BaseResponse createResponse(HttpStatus status, BindingResult result) { BaseResponse response = new BaseResponse(); if (result.hasErrors()) { response.setError(true); response.setHttpErrorCode(status.value()); /* create an array of total error count */ ArrayList<ErrorDTO> errors = new ArrayList<ErrorDTO>(result.getErrorCount()); /* append all field errors */ for (FieldError err : result.getFieldErrors()) { System.out.println( "I got field error for: " + err.getField() + ", message: " + err.getDefaultMessage() + ", code: " + err.getCode()); ErrorDTO dto = new ErrorDTO(err.getField(), err.getCode(), err.getDefaultMessage()); errors.add(dto); } /* append global errors now */ for (ObjectError err : result.getGlobalErrors()) { System.out.println( "I got global error for: " + err.getObjectName() + ", message: " + err.getDefaultMessage() + ", code: " + err.getCode()); ErrorDTO dto = new ErrorDTO(err.getObjectName(), err.getCode(), err.getDefaultMessage()); errors.add(dto); } response.setErrors(errors); } return response; }
@RequestMapping(value = "curso/{codigo}/estrutura/adicionar", method = RequestMethod.POST) public String adicionar( @Valid EstruturaCurricular estruturaCurricular, BindingResult result, @PathVariable("codigo") Integer codigo, RedirectAttributes redirectAttributes, ModelMap modelMap) { Curso curso = this.cursoService.getCursoByCodigo(codigo); modelMap.addAttribute("curso", curso); if (result.hasErrors()) { return "curso/estrutura/adicionar"; } if (estruturaCurricular.getCodigo().trim().isEmpty()) { result.rejectValue("codigo", "Repeat.estrutura.codigo", "Campo obrigatório."); return "curso/estrutura/adicionar"; } if (estruturaCurricularService.getOutraEstruturaCurricularByCodigo( curso.getCodigo(), estruturaCurricular.getCodigo()) != null) { result.rejectValue( "codigo", "Repeat.estruturas.codigo", "Ano e Semestre já existe para curso"); return "curso/estrutura/adicionar"; } estruturaCurricular.setCurso(curso); estruturaCurricular.setId(null); estruturaCurricularService.save(estruturaCurricular); redirectAttributes.addFlashAttribute("info", "Estrutura Curricular adicionada com sucesso."); return "redirect:/curso/" + curso.getCodigo() + "/visualizar"; }
@Override public void validate(Tag tag, BindingResult result) { Tag databaseTag; if (tag.getName().trim().equals("")) { result.rejectValue("name", null, null, "This field cannot be blank"); } if (containsHTML(tag.getName())) { LOG.error(HTML_ERROR); result.rejectValue("name", null, null, HTML_ERROR); } if (tag.getType() == null) { result.rejectValue("type", null, null, "This field cannot be blank"); } else { // Checking if type is valid TagType type = TagType.getTagType(tag.getType().toString()); databaseTag = loadTagWithType(tag.getName().trim(), type); if (databaseTag != null && (tag.getId() == null || !databaseTag.getId().equals(tag.getId()))) { result.rejectValue("name", MessageConstants.ERROR_NAMETAKEN); } // Check if updating tag is enterprise tag if (tag.getId() != null) { databaseTag = loadTag(tag.getId()); if (databaseTag == null || (databaseTag.getEnterpriseTag() != null && databaseTag.getEnterpriseTag())) { result.rejectValue("name", MessageConstants.ERROR_INVALID, new String[] {"Tag Id"}, null); } } } }