List of usage examples for org.springframework.validation BindingResult getAllErrors
List<ObjectError> getAllErrors();
From source file:nl.surfnet.coin.selfservice.control.requests.LinkrequestController.java
private ModelAndView doSubmitConfirm(Map<String, Object> m, AbstractAction abstractAction, BindingResult result, InstitutionIdentityProvider selectedIdp, SessionStatus sessionStatus, String errorViewName, String successViewName, String thanksTextKey) { if (result.hasErrors()) { LOG.debug("Errors in data binding, will return to form view: {}", result.getAllErrors()); return new ModelAndView(errorViewName, m); } else {/*from w w w . j a va 2s.c o m*/ final CoinUser currentUser = SpringSecurity.getCurrentUser(); String content = abstractAction instanceof LinkRequest ? ((LinkRequest) abstractAction).getNotes() : ((Question) abstractAction).getBody(); Action action = new Action(currentUser.getUid(), currentUser.getEmail(), currentUser.getUsername(), abstractAction.getType(), content, selectedIdp.getId(), abstractAction.getServiceProviderId(), selectedIdp.getInstitutionId()); if (abstractAction.getType().equals(JiraTask.Type.QUESTION)) { action.setSubject(((Question) abstractAction).getSubject()); } Action createdAction = csa.createAction(action); String issueKey = createdAction.getJiraKey(); m.put("issueKey", issueKey); m.put("abstractAction", abstractAction); m.put("thanksTextKey", thanksTextKey); } sessionStatus.setComplete(); return new ModelAndView(successViewName, m); }
From source file:fragment.web.AbstractBaseControllerTest.java
@Test public void testHandleAjaxFormValidationException() { FieldError error = new FieldError("tenant", "teannt", "Invalid Tenant"); List<ObjectError> lstError = new ArrayList<ObjectError>(); lstError.add(error);// www. jav a 2 s.co m BindingResult result = EasyMock.createMock(BindingResult.class); EasyMock.expect(result.getAllErrors()).andReturn(lstError).anyTimes(); EasyMock.replay(result); Errors errors = new BindException(result); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView mav = controller.handleAjaxFormValidationException(new AjaxFormValidationException(errors), new MockHttpServletRequest(), response); Assert.assertNotNull(mav.getModelMap()); Assert.assertEquals(420, response.getStatus()); // ModelAndViewAssert.assertViewName(mav, expectedName); }
From source file:mx.edu.um.mateo.inventario.web.AlmacenController.java
@RequestMapping(value = "/crea", method = RequestMethod.POST) public String crea(HttpSession session, @Valid Almacen almacen, BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes) { if (bindingResult.hasErrors()) { log.debug("Hubo algun error en la forma, regresando"); for (ObjectError error : bindingResult.getAllErrors()) { log.debug("Error: {}", error); }/* w w w . j a va 2s. c o m*/ return "inventario/almacen/nuevo"; } try { Usuario usuario = ambiente.obtieneUsuario(); almacen = almacenDao.crea(almacen, usuario); ambiente.actualizaSesion(session, usuario); } catch (ConstraintViolationException e) { log.error("No se pudo crear al almacen", e); errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null); return "inventario/almacen/nuevo"; } redirectAttributes.addFlashAttribute("message", "almacen.creado.message"); redirectAttributes.addFlashAttribute("messageAttrs", new String[] { almacen.getNombre() }); return "redirect:/inventario/almacen/ver/" + almacen.getId(); }
From source file:mx.edu.um.mateo.inventario.web.AlmacenController.java
@RequestMapping(value = "/actualiza", method = RequestMethod.POST) public String actualiza(HttpSession session, @Valid Almacen almacen, BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes) { if (bindingResult.hasErrors()) { log.error("Hubo algun error en la forma, regresando"); for (ObjectError error : bindingResult.getAllErrors()) { log.debug("Error: {}", error); }/* w ww . java 2 s .c o m*/ return "inventario/almacen/edita"; } try { Usuario usuario = ambiente.obtieneUsuario(); almacen = almacenDao.actualiza(almacen, usuario); ambiente.actualizaSesion(session, usuario); } catch (ConstraintViolationException e) { log.error("No se pudo crear la almacen", e); errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null); return "inventario/almacen/edita"; } redirectAttributes.addFlashAttribute("message", "almacen.actualizado.message"); redirectAttributes.addFlashAttribute("messageAttrs", new String[] { almacen.getNombre() }); return "redirect:/inventario/almacen/ver/" + almacen.getId(); }
From source file:org.openmrs.module.billing.web.controller.main.BillableServiceBillAddController.java
@RequestMapping(method = RequestMethod.POST) public String onSubmit(Model model, Object command, BindingResult bindingResult, HttpServletRequest request, @RequestParam("cons") Integer[] cons, @RequestParam("patientId") Integer patientId) { validate(cons, bindingResult, request); if (bindingResult.hasErrors()) { model.addAttribute("errors", bindingResult.getAllErrors()); return "module/billing/main/billableServiceBillEdit"; }//from w ww . j a va 2s .c om BillingService billingService = Context.getService(BillingService.class); PatientService patientService = Context.getPatientService(); // Get the BillCalculator to calculate the rate of bill item the patient has to pay Patient patient = patientService.getPatient(patientId); Map<String, String> attributes = PatientUtils.getAttributes(patient); BillCalculatorService calculator = new BillCalculatorService(); PatientServiceBill bill = new PatientServiceBill(); bill.setCreatedDate(new Date()); bill.setPatient(patient); bill.setCreator(Context.getAuthenticatedUser()); PatientServiceBillItem item; int quantity = 0; Money itemAmount; Money mUnitPrice; Money totalAmount = new Money(BigDecimal.ZERO); BigDecimal totalActualAmount = new BigDecimal(0); BigDecimal unitPrice; String name; BillableService service; for (int conceptId : cons) { unitPrice = NumberUtils.createBigDecimal(request.getParameter(conceptId + "_unitPrice")); quantity = NumberUtils.createInteger(request.getParameter(conceptId + "_qty")); name = request.getParameter(conceptId + "_name"); service = billingService.getServiceByConceptId(conceptId); mUnitPrice = new Money(unitPrice); itemAmount = mUnitPrice.times(quantity); totalAmount = totalAmount.plus(itemAmount); item = new PatientServiceBillItem(); item.setCreatedDate(new Date()); item.setName(name); item.setPatientServiceBill(bill); item.setQuantity(quantity); item.setService(service); item.setUnitPrice(unitPrice); item.setAmount(itemAmount.getAmount()); // Get the ratio for each bill item Map<String, Object> parameters = HospitalCoreUtils.buildParameters("patient", patient, "attributes", attributes, "billItem", item, "request", request); BigDecimal rate = calculator.getRate(parameters); item.setActualAmount(item.getAmount().multiply(rate)); totalActualAmount = totalActualAmount.add(item.getActualAmount()); bill.addBillItem(item); } bill.setAmount(totalAmount.getAmount()); bill.setActualAmount(totalActualAmount); bill.setFreeBill(calculator.isFreeBill(HospitalCoreUtils.buildParameters("attributes", attributes))); logger.info("Is free bill: " + bill.getFreeBill()); bill.setReceipt(billingService.createReceipt()); bill = billingService.savePatientServiceBill(bill); return "redirect:/module/billing/patientServiceBill.list?patientId=" + patientId + "&billId=" + bill.getPatientServiceBillId(); }
From source file:org.openmrs.module.cohort.web.controller.AddCohortMemberAttributeTypeController.java
@RequestMapping(value = "/module/cohort/addCohortMemberAttributeType.form", method = RequestMethod.POST) public String onSubmit(WebRequest request, HttpSession httpSession, ModelMap model, @ModelAttribute("cohortattributes") CohortMemberAttributeType cohortMemberAttributeType, BindingResult errors) { CohortService departmentService = Context.getService(CohortService.class); String voided = request.getParameter("voided"); String format = request.getParameter("format"); this.validator.validate(cohortMemberAttributeType, errors); if (errors.hasErrors()) { System.out.println("BR has errors: " + errors.getErrorCount()); System.out.println(errors.getAllErrors()); return "/module/cohort/addCohortMemberAttributeType"; } else {//from w ww.j av a 2 s. c o m cohortMemberAttributeType.setFormat(format); departmentService.saveCohortMemberAttributeType(cohortMemberAttributeType); httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "insertion success"); } return null; }
From source file:cn.loveapple.service.controller.contents.action.SiteController.java
/** * ?/*from w w w . jav a 2 s . co m*/ * * @param session * @param model * @return */ @RequestMapping(value = "core/registConfirm", method = RequestMethod.POST) public String registConfirm(@Valid SiteForm form, BindingResult result, HttpSession session, Model model, Locale locale) { model.addAttribute(form); SiteValidator validator = new SiteValidator(messageSource, locale); if (result.hasErrors()) { if (log.isDebugEnabled()) { log.debug(ToStringBuilder.reflectionToString(result.getAllErrors())); } return "core/regist"; } SiteModel siteModel = siteContentsService.findSite(form.getUnixName()); if (siteModel != null) { result.reject("loveappleErrors.beRegisted", validator.createArgs("msg.site"), ""); return "core/regist"; } session.setAttribute(FORM, form); return "core/registConfirm"; }
From source file:com.epam.cme.storefront.controllers.pages.TelcoCartPageController.java
/** * Handle the delete of a bundle/*from w w w.j a va2 s .c o m*/ * * @param form * bundle delete form, indicating the bundle No * @param model * @param bindingResult * @param redirectModel * @return redirect url * @throws CMSItemNotFoundException */ @RequestMapping(value = "/delete", method = RequestMethod.POST) public String deleteCartBundle(@Valid final DeleteBundleForm form, final Model model, final BindingResult bindingResult, final RedirectAttributes redirectModel) throws CMSItemNotFoundException { if (bindingResult.hasErrors()) { for (final ObjectError error : bindingResult.getAllErrors()) { GlobalMessages.addErrorMessage(model, error.getDefaultMessage()); } } try { cartFacade.deleteCartBundle(form.getBundleNo()); // Success in removing entry redirectModel.addFlashAttribute(GlobalMessages.CONF_MESSAGES_HOLDER, Collections.singletonList("basket.page.bundle.message.remove")); } catch (final CommerceCartModificationException e) { LOG.info("Could not delete bundle No" + form.getBundleNo()); redirectModel.addFlashAttribute(GlobalMessages.CONF_MESSAGES_HOLDER, Collections.singletonList("basket.page.bundle.message.remove.error")); } prepareDataForPage(model); return REDIRECT_PREFIX + "/cart"; }
From source file:es.ucm.fdi.dalgs.user.web.UserController.java
@RequestMapping(value = "/user/upload.htm", method = RequestMethod.POST) public String uploadPost(@ModelAttribute("newUpload") @Valid UploadForm upload, BindingResult resultBinding, Model model, RedirectAttributes attr, Locale locale) { if (resultBinding.hasErrors() || upload.getCharset().isEmpty() || upload.getFileData().getSize() == 0) { for (ObjectError error : resultBinding.getAllErrors()) { System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage()); }//from w ww .j a v a 2 s .c o m return "upload"; } ResultClass<Boolean> result = serviceUser.uploadCVS(upload, typeOfUser, locale); if (!result.hasErrors()) return "redirect:/user/page/0.htm?showAll=" + showAll + "&typeOfUser=" + typeOfUser; else { attr.addFlashAttribute("errors", result.getErrorsList()); return "redirect:/user/upload.htm"; } }
From source file:com.epam.training.storefront.controllers.pages.TelcoCartPageController.java
@RequestMapping(value = "/update", method = RequestMethod.POST) public String updateCartQuantities(@RequestParam("entryNumber") final long entryNumber, final Model model, @Valid final UpdateQuantityForm form, final BindingResult bindingResult, final RedirectAttributes redirectModel) throws CMSItemNotFoundException { if (bindingResult.hasErrors()) { for (final ObjectError error : bindingResult.getAllErrors()) { if (error.getCode().equals("typeMismatch")) { GlobalMessages.addErrorMessage(model, "basket.error.quantity.invalid"); } else { GlobalMessages.addErrorMessage(model, error.getDefaultMessage()); }// w ww . j a v a2 s . co m } } else if (cartFacade.getSessionCart().getEntries() != null) { try { final CartModificationData cartModification = cartFacade.updateCartEntry(entryNumber, form.getQuantity().longValue()); if (cartModification.getQuantity() == form.getQuantity().longValue()) { // Success if (cartModification.getQuantity() == 0) { // Success in removing entry redirectModel.addFlashAttribute(GlobalMessages.CONF_MESSAGES_HOLDER, Collections.singletonList("basket.page.message.remove")); } else { // Success in update quantity redirectModel.addFlashAttribute(GlobalMessages.CONF_MESSAGES_HOLDER, Collections.singletonList("basket.page.message.update")); } } else { // Less than successful if (form.getQuantity().longValue() == 0) { // Failed to remove entry redirectModel.addFlashAttribute(GlobalMessages.ERROR_MESSAGES_HOLDER, Collections.singletonList("basket.information.quantity.reducedNumberOfItemsAdded." + cartModification.getStatusCode())); } else { // Failed to update quantity redirectModel.addFlashAttribute(GlobalMessages.ERROR_MESSAGES_HOLDER, Collections.singletonList("basket.information.quantity.reducedNumberOfItemsAdded." + cartModification.getStatusCode())); } } // Redirect to the cart page on update success so that the browser doesn't re-post again return REDIRECT_PREFIX + "/cart"; } catch (final CommerceCartModificationException ex) { LOG.warn("Couldn't update product with the entry number: " + entryNumber + ".", ex); } } prepareDataForPage(model); return ControllerConstants.Views.Pages.Cart.CartPage; }