Example usage for org.springframework.validation BindingResult getAllErrors

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

Introduction

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

Prototype

List<ObjectError> getAllErrors();

Source Link

Document

Get all errors, both global and field ones.

Usage

From source file:org.openmrs.module.billing.web.controller.main.BillableServiceBillEditController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(Model model, Object command, BindingResult bindingResult, HttpServletRequest request,
        @RequestParam("cons") Integer[] cons, @RequestParam("patientId") Integer patientId,
        @RequestParam("billId") Integer billId, @RequestParam("action") String action,
        @RequestParam(value = "description", required = false) String description) {

    validate(cons, bindingResult, request);
    if (bindingResult.hasErrors()) {
        model.addAttribute("errors", bindingResult.getAllErrors());
        return "module/billing/main/patientServiceBillEdit";
    }/*w  w w .j  a  va  2s  .  co  m*/
    BillingService billingService = Context.getService(BillingService.class);

    PatientServiceBill bill = billingService.getPatientServiceBillById(billId);

    // Get the BillCalculator to calculate the rate of bill item the patient
    // has to pay
    Patient patient = Context.getPatientService().getPatient(patientId);
    Map<String, String> attributes = PatientUtils.getAttributes(patient);
    BillCalculatorService calculator = new BillCalculatorService();

    if (!"".equals(description))
        bill.setDescription(description);

    if ("void".equalsIgnoreCase(action)) {
        bill.setVoided(true);
        bill.setVoidedDate(new Date());
        for (PatientServiceBillItem item : bill.getBillItems()) {
            item.setVoided(true);
            item.setVoidedDate(new Date());
            /*ghanshyam 7-sept-2012 these 5 lines of code written only due to voided item is being updated in "billing_patient_service_bill_item" table
              but not being updated in "orders" table */
            Order ord = item.getOrder();
            if (ord != null) {
                ord.setVoided(true);
                ord.setDateVoided(new Date());
            }
            item.setOrder(ord);
        }
        billingService.savePatientServiceBill(bill);
        //ghanshyam 7-sept-2012 Support #343 [Billing][3.2.7-SNAPSHOT]No Queue to be generated from Old bill
        return "redirect:/module/billing/patientServiceBillEdit.list?patientId=" + patientId;
    }

    // void old items and reset amount
    Map<Integer, PatientServiceBillItem> mapOldItems = new HashMap<Integer, PatientServiceBillItem>();
    for (PatientServiceBillItem item : bill.getBillItems()) {
        item.setVoided(true);
        item.setVoidedDate(new Date());
        //ghanshyam-kesav 16-08-2012 Bug #323 [BILLING] When a bill with a lab\radiology order is edited the order is re-sent
        Order ord = item.getOrder();
        /*ghanshyam 18-08-2012 [Billing - Bug #337] [3.2.7 snap shot][billing(DDU,DDU SDMX,Tanda,mohali)]error in edit bill.
          the problem was while we are editing the bill of other than lab and radiology.
        */
        if (ord != null) {
            ord.setVoided(true);
            ord.setDateVoided(new Date());
        }
        item.setOrder(ord);
        mapOldItems.put(item.getPatientServiceBillItemId(), item);
    }
    bill.setAmount(BigDecimal.ZERO);
    bill.setPrinted(false);

    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);

        String sItemId = request.getParameter(conceptId + "_itemId");

        if (sItemId == null) {
            item = new PatientServiceBillItem();

            // Get the ratio for each bill item
            Map<String, Object> parameters = HospitalCoreUtils.buildParameters("patient", patient, "attributes",
                    attributes, "billItem", item);
            BigDecimal rate = calculator.getRate(parameters);

            item.setAmount(itemAmount.getAmount());
            item.setActualAmount(item.getAmount().multiply(rate));
            totalActualAmount = totalActualAmount.add(item.getActualAmount());
            item.setCreatedDate(new Date());
            item.setName(name);
            item.setPatientServiceBill(bill);
            item.setQuantity(quantity);
            item.setService(service);
            item.setUnitPrice(unitPrice);
            bill.addBillItem(item);
        } else {

            item = mapOldItems.get(Integer.parseInt(sItemId));

            // Get the ratio for each bill item
            Map<String, Object> parameters = HospitalCoreUtils.buildParameters("patient", patient, "attributes",
                    attributes, "billItem", item);
            BigDecimal rate = calculator.getRate(parameters);

            //ghanshyam 5-oct-2012 [Billing - Support #344] [Billing] Edited Quantity and Amount information is lost in database
            if (quantity != item.getQuantity()) {
                item.setVoided(true);
                item.setVoidedDate(new Date());
            } else {
                item.setVoided(false);
                item.setVoidedDate(null);
            }
            // ghanshyam-kesav 16-08-2012 Bug #323 [BILLING] When a bill with a lab\radiology order is edited the order is re-sent
            Order ord = item.getOrder();
            if (ord != null) {
                ord.setVoided(false);
                ord.setDateVoided(null);
            }
            item.setOrder(ord);
            //ghanshyam 5-oct-2012 [Billing - Support #344] [Billing] Edited Quantity and Amount information is lost in database
            if (quantity != item.getQuantity()) {
                item = new PatientServiceBillItem();
                item.setService(service);
                item.setUnitPrice(unitPrice);
                item.setQuantity(quantity);
                item.setName(name);
                item.setCreatedDate(new Date());
                item.setOrder(ord);
                bill.addBillItem(item);
            }
            item.setAmount(itemAmount.getAmount());
            item.setActualAmount(item.getAmount().multiply(rate));
            totalActualAmount = totalActualAmount.add(item.getActualAmount());
        }
    }
    bill.setAmount(totalAmount.getAmount());
    bill.setActualAmount(totalActualAmount);

    // Determine whether the bill is free or not

    bill.setFreeBill(calculator.isFreeBill(HospitalCoreUtils.buildParameters("attributes", attributes)));
    logger.info("Is free bill: " + bill.getFreeBill());

    bill = billingService.savePatientServiceBill(bill);
    //ghanshyam 7-sept-2012 Support #343 [Billing][3.2.7-SNAPSHOT]No Queue to be generated from Old bill
    return "redirect:/module/billing/patientServiceBillEdit.list?patientId=" + patientId + "&billId=" + billId;
}

From source file:wad.controller.ReceiptController.java

@RequestMapping(method = RequestMethod.POST)
public String addReceipt(@RequestParam("file") MultipartFile file, @PathVariable Long expenseId,
        @ModelAttribute Receipt receipt, BindingResult bindingResult, @ModelAttribute Expense expense,
        SessionStatus status, RedirectAttributes redirectAttrs) throws IOException {

    if (expense == null || !expense.isEditableBy(userService.getCurrentUser())) {
        throw new ResourceNotFoundException();
    }//  w  w w  .  j av  a 2 s.c  om

    receipt.setName(file.getName());
    receipt.setMediaType(file.getContentType());
    receipt.setSize(file.getSize());
    receipt.setContent(file.getBytes());
    receipt.setSubmitted(new Date());
    receipt.setExpense(expense);

    receiptValidator.validate(receipt, bindingResult);

    if (bindingResult.hasErrors()) {
        redirectAttrs.addFlashAttribute("errors", bindingResult.getAllErrors());
        return "redirect:/expenses/" + expense.getId();
    }

    receiptRepository.save(receipt);

    status.setComplete();

    return "redirect:/expenses/" + expense.getId();
}

From source file:com.askme.controller.app.AppController.java

@RequestMapping(value = "/question/ask", method = RequestMethod.POST)
public String postAskQuestion(@Valid Question question, BindingResult result, ModelMap model,
        RedirectAttributes redirect) {//from   ww w  .j  a v  a 2s . co m
    // Header and sidebar data
    List<Category> categories = categoryService.findAll();
    List<Tag> tags = tagService.findAll();
    model.addAttribute("categories", categories);
    model.addAttribute("tags", tags);

    if (result.hasErrors()) {
        System.out.println(result.getAllErrors());
        return "question_form";
    }

    question.setSlug(StringUtil.slugify(question.getTitle()));
    question.setCreatedAt(new Date());
    question.setUpdatedAt(new Date());
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    User currentUser = ((CustomUserDetails) principal).getUser();
    question.setUser(currentUser);
    questionService.save(question);

    redirect.addFlashAttribute("success", "Cu h?i ca bn  c to thnh cng!");
    return "redirect:/question/ask";
}

From source file:com.rr.generic.ui.users.userController.java

/**
* The '/user.create' POST request will handle submitting the new staff member.
*
* @param userDetails    The object containing the user form fields
* @param result          The validation result
* @param redirectAttr    The variable that will hold values that can be read after the redirect
*
* @return   Will send the program admin to the details of the new staff member
        //from  www. j ava2 s. c o m
* @throws Exception
*/
@RequestMapping(value = "/user.create", method = RequestMethod.POST)
public @ResponseBody ModelAndView saveStaffMember(
        @Valid @ModelAttribute(value = "userDetails") User newuserDetails, BindingResult result,
        HttpSession session) throws Exception {

    if (result.hasErrors()) {

        for (ObjectError error : result.getAllErrors()) {
            System.out.println("Error: " + error.getDefaultMessage());
        }

        ModelAndView mav = new ModelAndView();
        mav.setViewName("/users/newUser");
        return mav;
    }

    /* Check for duplicate email address */
    User existingUser = usermanager.checkDuplicateUsername(newuserDetails.getUsername(), programId, 0);

    if (existingUser != null) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/users/newUser");
        mav.addObject("existingUser", "The username is already being used by another user.");
        return mav;
    }

    /* Get a list of completed surveys the logged in user has access to */
    User userDetails = (User) session.getAttribute("userDetails");

    newuserDetails.setCreatedBy(userDetails.getId());
    newuserDetails.setRoleId(3);

    newuserDetails = usermanager.encryptPW(newuserDetails);
    Integer userId = usermanager.createUser(newuserDetails);

    /* associate user to program */
    userPrograms program = new userPrograms();
    program.setProgramId(programId);
    program.setsystemUserId(userId);
    programmanager.saveUserProgram(program);

    Map<String, String> map = new HashMap<String, String>();
    map.put("id", Integer.toString(userId));
    map.put("topSecret", topSecret);

    encryptObject encrypt = new encryptObject();

    String[] encrypted = encrypt.encryptObject(map);

    ModelAndView mav = new ModelAndView();
    mav.setViewName("/users/newUser");
    mav.addObject("encryptedURL", "?i=" + encrypted[0] + "&v=" + encrypted[1]);
    return mav;

}

From source file:es.ucm.fdi.dalgs.group.web.GroupController.java

@RequestMapping(value = "/academicTerm/{academicId}/course/{courseId}/group/{groupId}/{typeOfUser}/upload.htm", method = RequestMethod.POST)
public String uploadUserPost(@ModelAttribute("newUpload") @Valid UploadForm upload, BindingResult resultBinding,
        Model model, @PathVariable("academicId") Long id_academic, @PathVariable("courseId") Long id_course,
        @PathVariable("groupId") Long id_group, @PathVariable("typeOfUser") String typeOfUser, Locale locale,
        RedirectAttributes attr) {// w ww  .  java  2 s. co  m

    logger.info("Upload POST USERS: " + typeOfUser);

    if (resultBinding.hasErrors() || upload.getCharset().isEmpty()) {
        for (ObjectError error : resultBinding.getAllErrors()) {
            System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
        }
        return "upload";
    }

    Group group = serviceGroup.getGroup(id_group, id_course, id_academic, false).getSingleElement();

    boolean success = !serviceGroup.removeUsersFromGroup(group, typeOfUser, id_academic, id_course).hasErrors();
    if (success) {
        ResultClass<Boolean> result = serviceGroup.uploadUserCVS(group, upload, typeOfUser, locale);

        if (!result.hasErrors()) {
            return "redirect:/academicTerm/" + id_academic + "/course/" + id_course + "/group/" + id_group
                    + ".htm";
        } else
            attr.addFlashAttribute("errors", result.getErrorsList());
        return "redirect:/academicTerm/" + id_academic + "/course/" + id_course + "/group/" + id_group + "/"
                + typeOfUser + "/upload.htm";
    } else {

        return "redirect:/academicTerm/" + id_academic + "/course/" + id_course + "/group/" + id_group + "/"
                + typeOfUser + "/upload.htm";
    }
}

From source file:org.dspace.EDMExport.controller.homeController.java

/**
 * Mtodo para logar los errores del objeto que une los datos de la peticin
 * /*from  ww w  .  jav a 2 s  .c  o m*/
 * @param result objeto que une la peticin {@link BindingResult}
 */
private void logErrorValid(BindingResult result) {
    for (Object object : result.getAllErrors()) {
        if (object instanceof FieldError) {
            FieldError fieldError = (FieldError) object;
            logger.debug(fieldError.toString());
        }
    }
}

From source file:mvc.MessageController.java

/**
 *  ? /*from  w w w.  j  a va2  s . c  o  m*/
 *
 * @param model
 * @param obj
 * @param bindRes
 * @param orderId
 * @param files
 * @param attr
 * @return
 * @throws IOException
 * @throws NotRightException
 */
@RequestMapping("/addAdmin")
public String addAdminMessage(Map<String, Object> model,
        @ModelAttribute("adminMessage") @Valid AdminMessage obj, BindingResult bindRes,
        @RequestParam("orderId") Long orderId,
        @RequestParam(value = "file", required = false) MultipartFile[] files, RedirectAttributes attr)
        throws IOException, NotRightException {

    checkBranchRight(orderId, "/Message/addAdmin");

    String errorAttrName = "errors";
    if (!bindRes.hasErrors()) {
        ServiceResult res = messageService.addAdminMessage(obj, files, orderId);
        if (res.hasErrors()) {
            attr.addFlashAttribute(errorAttrName, res.getErrors());
        }
    } else {
        attr.addFlashAttribute(errorAttrName, bindRes.getAllErrors());
    }
    return "redirect:/Order/get?orderId=" + orderId;
}

From source file:org.openmrs.module.billing.web.controller.main.BillableServiceBillEditForBDController.java

@RequestMapping(method = RequestMethod.POST)
public String onSubmit(Model model, Object command, BindingResult bindingResult, HttpServletRequest request,
        @RequestParam("cons") Integer[] cons, @RequestParam("patientId") Integer patientId,
        @RequestParam("billId") Integer billId, @RequestParam("action") String action,
        @RequestParam(value = "description", required = false) String description) {

    validate(cons, bindingResult, request);
    if (bindingResult.hasErrors()) {
        model.addAttribute("errors", bindingResult.getAllErrors());
        return "module/billing/main/patientServiceBillEdit";
    }// www  .  j a  va 2s. co m
    BillingService billingService = Context.getService(BillingService.class);

    PatientServiceBill bill = billingService.getPatientServiceBillById(billId);

    // Get the BillCalculator to calculate the rate of bill item the patient
    // has to pay
    Patient patient = Context.getPatientService().getPatient(patientId);
    Map<String, String> attributes = PatientUtils.getAttributes(patient);

    BillCalculatorForBDService calculator = new BillCalculatorForBDService();

    if (!"".equals(description))
        bill.setDescription(description);

    if ("void".equalsIgnoreCase(action)) {
        bill.setVoided(true);
        bill.setVoidedDate(new Date());
        for (PatientServiceBillItem item : bill.getBillItems()) {
            item.setVoided(true);
            item.setVoidedDate(new Date());
            /*ghanshyam 7-sept-2012 these 5 lines of code written only due to voided item is being updated in "billing_patient_service_bill_item" table
              but not being updated in "orders" table */
            Order ord = item.getOrder();
            if (ord != null) {
                ord.setVoided(true);
                ord.setDateVoided(new Date());
            }
            item.setOrder(ord);
        }
        billingService.savePatientServiceBill(bill);
        //ghanshyam 7-sept-2012 Support #343 [Billing][3.2.7-SNAPSHOT]No Queue to be generated from Old bill
        return "redirect:/module/billing/patientServiceBillEditForBD.list?patientId=" + patientId;
    }

    // void old items and reset amount
    Map<Integer, PatientServiceBillItem> mapOldItems = new HashMap<Integer, PatientServiceBillItem>();
    for (PatientServiceBillItem item : bill.getBillItems()) {
        item.setVoided(true);
        item.setVoidedDate(new Date());
        //ghanshyam-kesav 16-08-2012 Bug #323 [BILLING] When a bill with a lab\radiology order is edited the order is re-sent
        Order ord = item.getOrder();
        /*ghanshyam 18-08-2012 [Billing - Bug #337] [3.2.7 snap shot][billing(DDU,DDU SDMX,Tanda,mohali)]error in edit bill.
          the problem was while we are editing the bill of other than lab and radiology.
        */
        if (ord != null) {
            ord.setVoided(true);
            ord.setDateVoided(new Date());
        }
        item.setOrder(ord);
        mapOldItems.put(item.getPatientServiceBillItemId(), item);
    }
    bill.setAmount(BigDecimal.ZERO);
    bill.setPrinted(false);

    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);

        String sItemId = request.getParameter(conceptId + "_itemId");

        if (sItemId == null) {
            item = new PatientServiceBillItem();

            // Get the ratio for each bill item
            Map<String, Object> parameters = HospitalCoreUtils.buildParameters("patient", patient, "attributes",
                    attributes, "billItem", item);
            BigDecimal rate;
            //ghanshyam 25-02-2013 New Requirement #966[Billing]Add Paid Bill/Add Free Bill for Bangladesh module
            //ghanshyam 3-june-2013 New Requirement #1632 Orders from dashboard must be appear in billing queue.User must be able to generate bills from this queue
            if (bill.getFreeBill().equals(1)) {
                String billType = "free";
                rate = calculator.getRate(parameters, billType);
            } else if (bill.getFreeBill().equals(2)) {
                String billType = "mixed";
                PatientServiceBillItem patientServiceBillItem = billingService.getPatientServiceBillItem(billId,
                        name);
                String psbi = patientServiceBillItem.getActualAmount().toString();
                if (psbi.equals("0.00")) {
                    rate = new BigDecimal(0);
                } else {
                    rate = new BigDecimal(1);
                }
                item.setActualAmount(item.getAmount().multiply(rate));
            } else {
                String billType = "paid";
                rate = calculator.getRate(parameters, billType);
            }

            item.setAmount(itemAmount.getAmount());
            item.setActualAmount(item.getAmount().multiply(rate));
            totalActualAmount = totalActualAmount.add(item.getActualAmount());
            item.setCreatedDate(new Date());
            item.setName(name);
            item.setPatientServiceBill(bill);
            item.setQuantity(quantity);
            item.setService(service);
            item.setUnitPrice(unitPrice);
            bill.addBillItem(item);
        } else {

            item = mapOldItems.get(Integer.parseInt(sItemId));

            // Get the ratio for each bill item
            Map<String, Object> parameters = HospitalCoreUtils.buildParameters("patient", patient, "attributes",
                    attributes, "billItem", item);
            BigDecimal rate;
            //ghanshyam 25-02-2013 New Requirement #966[Billing]Add Paid Bill/Add Free Bill for Bangladesh module
            //ghanshyam 3-june-2013 New Requirement #1632 Orders from dashboard must be appear in billing queue.User must be able to generate bills from this queue
            if (bill.getFreeBill().equals(1)) {
                String billType = "free";
                rate = calculator.getRate(parameters, billType);
            } else if (bill.getFreeBill().equals(2)) {
                String billType = "mixed";
                PatientServiceBillItem patientServiceBillItem = billingService.getPatientServiceBillItem(billId,
                        name);
                String psbi = patientServiceBillItem.getActualAmount().toString();
                if (psbi.equals("0.00")) {
                    rate = new BigDecimal(0);
                } else {
                    rate = new BigDecimal(1);
                }
                item.setActualAmount(item.getAmount().multiply(rate));
            } else {
                String billType = "paid";
                rate = calculator.getRate(parameters, billType);
            }

            //ghanshyam 5-oct-2012 [Billing - Support #344] [Billing] Edited Quantity and Amount information is lost in database
            if (quantity != item.getQuantity()) {
                item.setVoided(true);
                item.setVoidedDate(new Date());
            } else {
                item.setVoided(false);
                item.setVoidedDate(null);
            }
            // ghanshyam-kesav 16-08-2012 Bug #323 [BILLING] When a bill with a lab\radiology order is edited the order is re-sent
            Order ord = item.getOrder();
            if (ord != null) {
                ord.setVoided(false);
                ord.setDateVoided(null);
            }
            item.setOrder(ord);
            //ghanshyam 5-oct-2012 [Billing - Support #344] [Billing] Edited Quantity and Amount information is lost in database
            if (quantity != item.getQuantity()) {
                item = new PatientServiceBillItem();
                item.setService(service);
                item.setUnitPrice(unitPrice);
                item.setQuantity(quantity);
                item.setName(name);
                item.setCreatedDate(new Date());
                item.setOrder(ord);
                bill.addBillItem(item);
            }
            item.setAmount(itemAmount.getAmount());
            item.setActualAmount(item.getAmount().multiply(rate));

            totalActualAmount = totalActualAmount.add(item.getActualAmount());
        }
    }
    bill.setAmount(totalAmount.getAmount());
    bill.setActualAmount(totalActualAmount);

    // Determine whether the bill is free or not

    //ghanshyam 25-02-2013 New Requirement #966[Billing]Add Paid Bill/Add Free Bill for Bangladesh module
    //ghanshyam 3-june-2013 New Requirement #1632 Orders from dashboard must be appear in billing queue.User must be able to generate bills from this queue
    if (bill.getFreeBill().equals(1)) {
        String billType = "free";
        bill.setFreeBill(calculator.isFreeBill(billType));
    } else if (bill.getFreeBill().equals(2)) {
        String billType = "mixed";
        bill.setFreeBill(2);
    } else {
        String billType = "paid";
        bill.setFreeBill(calculator.isFreeBill(billType));
    }

    logger.info("Is free bill: " + bill.getFreeBill());

    bill = billingService.savePatientServiceBill(bill);
    //ghanshyam 7-sept-2012 Support #343 [Billing][3.2.7-SNAPSHOT]No Queue to be generated from Old bill
    return "redirect:/module/billing/patientServiceBillEditForBD.list?patientId=" + patientId + "&billId="
            + billId;
}