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.BillableServiceBillAddForBDController.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(value = "comment", required = false) String comment,
        @RequestParam(value = "billType", required = false) String billType) {
    validate(cons, bindingResult, request);
    if (bindingResult.hasErrors()) {
        model.addAttribute("errors", bindingResult.getAllErrors());
        return "module/billing/main/billableServiceBillEdit";
    }//  w  w w . j a  va  2  s  . co m

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

    BillCalculatorForBDService calculator = new BillCalculatorForBDService();

    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, billType);
        item.setActualAmount(item.getAmount().multiply(rate));
        totalActualAmount = totalActualAmount.add(item.getActualAmount());

        bill.addBillItem(item);
    }
    bill.setAmount(totalAmount.getAmount());
    bill.setActualAmount(totalActualAmount);
    bill.setComment(comment);
    bill.setFreeBill(calculator.isFreeBill(billType));
    logger.info("Is free bill: " + bill.getFreeBill());

    bill.setReceipt(billingService.createReceipt());
    bill = billingService.savePatientServiceBill(bill);
    return "redirect:/module/billing/patientServiceBillForBD.list?patientId=" + patientId + "&billId="
            + bill.getPatientServiceBillId() + "&billType=" + billType;

}

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

@RequestMapping(method = RequestMethod.POST)
public String submit(@ModelAttribute("command") Object command, BindingResult binding,
        SessionStatus sessionStatus, @RequestParam("cons") Integer[] concepts, HttpServletRequest request,
        Model model) {/*from   w  w w.  j a va2 s  .co m*/

    ConceptService cs = Context.getConceptService();
    Integer root = Integer.valueOf(Context.getAdministrationService()
            .getGlobalProperty(BillingConstants.GLOBAL_PROPRETY_SERVICE_CONCEPT));
    validate(concepts, request, binding);
    if (binding.hasErrors()) {
        log.info(binding.getAllErrors());

        Concept concept = cs.getConcept(root);

        BillingService billingService = Context.getService(BillingService.class);

        List<BillableService> services = billingService.getAllServices();

        Map<Integer, BillableService> mapServices = new HashMap<Integer, BillableService>();

        for (BillableService ser : services) {
            if (ser.getPrice() != null)
                mapServices.put(ser.getConceptId(), ser);
        }

        model.addAttribute("errors", binding.getAllErrors());
        model.addAttribute("tree", billingService.traversServices(concept, mapServices));
        return "/module/billing/main/serviceManage";
    }

    BillingService billingService = Context.getService(BillingService.class);
    List<BillableService> services = billingService.getAllServices();

    Map<Integer, BillableService> mapServices = new HashMap<Integer, BillableService>();

    for (BillableService ser : services) {
        mapServices.put(ser.getConceptId(), ser);
    }
    for (int conId : concepts) {

        String name = request.getParameter(conId + "_name");
        String shortName = request.getParameter(conId + "_shortName");
        String price = request.getParameter(conId + "_price");
        String serviceTypeText = request.getParameter(conId + "_type");

        BillableService service = mapServices.get(conId);
        if (service == null) {
            service = new BillableService();
            service.setConceptId(conId);
            service.setName(name);
            service.setShortName(shortName);
            if (StringUtils.isNotBlank(price))
                service.setPrice(NumberUtils.createBigDecimal(price));
            mapServices.put(conId, service);
        } else {
            service.setName(name);
            service.setShortName(shortName);
            if (StringUtils.isNotBlank(price))
                service.setPrice(NumberUtils.createBigDecimal(price));
            mapServices.remove(conId);
            mapServices.put(conId, service);
        }
    }
    billingService.saveServices(mapServices.values());
    sessionStatus.setComplete();
    return "redirect:/module/billing/service.form";
}

From source file:com.ctc.storefront.controllers.pages.CartPageController.java

@RequestMapping(value = "/save", method = RequestMethod.POST)
@RequireHardLogIn//from ww  w  .j  a  v a2s . co m
public String saveCart(final SaveCartForm form, final BindingResult bindingResult,
        final RedirectAttributes redirectModel) throws CommerceSaveCartException {
    saveCartFormValidator.validate(form, bindingResult);
    if (bindingResult.hasErrors()) {
        for (final ObjectError error : bindingResult.getAllErrors()) {
            GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.ERROR_MESSAGES_HOLDER,
                    error.getCode());
        }
        redirectModel.addFlashAttribute("saveCartForm", form);
    } else {
        final CommerceSaveCartParameterData commerceSaveCartParameterData = new CommerceSaveCartParameterData();
        commerceSaveCartParameterData.setName(form.getName());
        commerceSaveCartParameterData.setDescription(form.getDescription());
        commerceSaveCartParameterData.setEnableHooks(true);
        try {
            final CommerceSaveCartResultData saveCartData = saveCartFacade
                    .saveCart(commerceSaveCartParameterData);
            GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
                    "basket.save.cart.on.success", new Object[] { saveCartData.getSavedCartData().getName() });
        } catch (final CommerceSaveCartException csce) {
            LOG.error(csce.getMessage(), csce);
            GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.ERROR_MESSAGES_HOLDER,
                    "basket.save.cart.on.error", new Object[] { form.getName() });
        }
    }
    return REDIRECT_CART_URL;
}

From source file:cn.loveapple.service.controller.member.action.MemberController.java

/**
 * ?//from   w  ww  .  j av  a2s.  co m
 * 
 * @param session
 * @param model
 * @return
 */
@RequestMapping(value = "registConfirm", method = RequestMethod.POST)
public String registConfirm(@Valid MemberForm form, BindingResult result, HttpSession session, Model model,
        Locale locale) {
    model.addAttribute(form);
    MemberValidator validator = new MemberValidator(messageSource, locale);
    validator.validate(form, result);
    if (result.hasErrors()) {
        if (log.isDebugEnabled()) {
            log.debug(ToStringBuilder.reflectionToString(result.getAllErrors()));
        }
        return "member/regist";
    }

    LoveappleMemberModel member = memberCoreService.findByEmail(form.getMail());
    if (member != null) {
        result.reject("loveappleErrors.beRegisted", validator.createArgs("msg.member"), "");
        return "member/regist";
    }

    member = createModel(form, locale);

    session.setAttribute(FORM, form);
    session.setAttribute(LOVEAPPLE_MEMBER_TMP, member);

    return "member/registConfirm";
}

From source file:es.ucm.fdi.dalgs.subject.web.SubjectController.java

@RequestMapping(value = "/degree/{degreeId}/module/{moduleId}/topic/{topicId}/subject/upload.htm", method = RequestMethod.POST)
public String uploadPost(@ModelAttribute("newUpload") @Valid UploadForm upload, BindingResult resultBinding,
        Model model, @PathVariable("degreeId") Long id_degree, @PathVariable("moduleId") Long id_module,
        @PathVariable("topicId") Long id_topic, 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());
        }/*  w  w  w. java 2  s  .  c  o m*/
        return "upload";
    }
    ResultClass<Boolean> result = serviceSubject.uploadCSV(upload, id_topic, id_module, id_degree, locale);
    if (!result.hasErrors())
        return "redirect:/degree/" + id_degree + "/module/" + id_module + "/topic/" + id_topic + ".htm";
    else {
        attr.addFlashAttribute("errors", result.getErrorsList());
        return "redirect:/degree/" + id_degree + "/module/" + id_module + "/topic/" + id_topic
                + "/subject/upload.htm";
    }
}

From source file:com.daimler.spm.storefront.controllers.pages.CartPageController.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 HttpServletRequest request, final RedirectAttributes redirectModel)
        throws CMSItemNotFoundException {
    if (bindingResult.hasErrors()) {
        for (final ObjectError error : bindingResult.getAllErrors()) {
            if ("typeMismatch".equals(error.getCode())) {
                GlobalMessages.addErrorMessage(model, "basket.error.quantity.invalid");
            } else {
                GlobalMessages.addErrorMessage(model, error.getDefaultMessage());
            }/*w  ww . j  a v a2s .c o m*/
        }
    } else if (getCartFacade().hasEntries()) {
        try {
            final CartModificationData cartModification = getCartFacade().updateCartEntry(entryNumber,
                    form.getQuantity().longValue());
            addFlashMessage(form, request, redirectModel, cartModification);

            final QuoteData quoteData = getCartFacade().getSessionCart().getQuoteData();

            // Redirect to the cart page on update success so that the browser doesn't re-post again
            return quoteData != null ? String.format(REDIRECT_QUOTE_EDIT_URL, urlEncode(quoteData.getCode()))
                    : REDIRECT_CART_URL;
        } catch (final CommerceCartModificationException ex) {
            LOG.warn("Couldn't update product with the entry number: " + entryNumber + ".", ex);
        }
    }

    // if could not update cart, display cart/quote page again with error
    return prepareCartUrl(model);
}

From source file:com.ctc.storefront.controllers.pages.CartPageController.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 HttpServletRequest request, final RedirectAttributes redirectModel,
        final HttpServletResponse response) throws CMSItemNotFoundException {
    if (bindingResult.hasErrors()) {
        for (final ObjectError error : bindingResult.getAllErrors()) {
            if ("typeMismatch".equals(error.getCode())) {
                GlobalMessages.addErrorMessage(model, "basket.error.quantity.invalid");
            } else {
                GlobalMessages.addErrorMessage(model, error.getDefaultMessage());
            }/*from  w ww . j  a v a  2s  .  co m*/
        }
    } else if (getCartFacade().hasEntries()) {
        try {
            final CartModificationData cartModification = getCartFacade().updateCartEntry(entryNumber,
                    form.getQuantity().longValue());
            addFlashMessage(form, request, redirectModel, cartModification);
            setCookie(response, getCartFacade().getSessionCart());

            // Redirect to the cart page on update success so that the browser doesn't re-post again
            return REDIRECT_CART_URL;
        } catch (final CommerceCartModificationException ex) {
            LOG.warn("Couldn't update product with the entry number: " + entryNumber + ".", ex);
        }
    }

    prepareDataForPage(model);

    return ControllerConstants.Views.Pages.Cart.CartPage;
}

From source file:net.sf.sze.frontend.zeugnis.ZeugnisController.java

/**
 * Speichert das vernderte Zeugnis./*from w w w.j  av  a2s .c o m*/
 * @param halbjahrId die Id des Schulhalbjahres
 * @param klassenId die Id der Klasse
 * @param schuelerId die Id des Schuelers
 * @param result das Bindingresult.
 * @param prevId die Id des vorherigen Schlers.
 * @param nextId die Id der nchsten Schlers.
 * @param action die als nchstes auszufhrende Aktion.
 * @param zeugnis das zu speichernde Zeugnis.
 * @param model das Model
 * @return die logische View
 */
@RequestMapping(value = URL.ZeugnisPath.ZEUGNIS_EDIT_DETAIL, method = RequestMethod.POST)
public String updateZeugnisDetail(@PathVariable(URL.Session.P_HALBJAHR_ID) Long halbjahrId,
        @PathVariable(URL.Session.P_KLASSEN_ID) Long klassenId,
        @PathVariable(URL.Session.P_SCHUELER_ID) Long schuelerId, @RequestParam(Common.P_PREV_ID) Long prevId,
        @RequestParam(Common.P_NEXT_ID) Long nextId,
        @RequestParam(value = Common.P_ACTION, required = false) String action,
        @ModelAttribute("zeugnis") Zeugnis zeugnis, BindingResult result, Model model) {
    validator.validate(zeugnis, result);
    if (result.hasErrors()) {
        LOG.info("Fehler:" + result.getAllErrors());
        fillZeugnisDetailModel(model, halbjahrId, klassenId, schuelerId, zeugnis, prevId, nextId);
        return EDIT_ZEUGNIS_DETAIL_VIEW;
    }

    LOG.debug("Update Zeugnis: " + zeugnis);
    zeugnisErfassungsService.save(zeugnis);
    return URL.getPrevNextUrlOrZeugnisUrl(action, URL.ZeugnisPath.ZEUGNIS_EDIT_DETAIL, halbjahrId, klassenId,
            schuelerId, prevId, nextId);
}

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

@RequestMapping(value = "/user/changeProfile", method = RequestMethod.POST)
public String postChangeProfile(@Valid User user, BindingResult result, ModelMap model,
        RedirectAttributes redirect, HttpServletRequest request,
        @RequestParam(value = "file", required = false) MultipartFile file) {
    passwordValidator.validate(user, result);
    if (result.hasErrors()) {
        System.out.println(result.getAllErrors());
        return "change_profile";
    }/*from ww w  .ja v  a  2  s .c  om*/

    // Upload avatar
    if (file != null) {
        try {
            InputStream inputStream = file.getInputStream();
            if (inputStream == null) {
                System.out.println("File inputstream is null");
            }
            String path = request.getServletContext().getRealPath("/") + "public/avatar/";
            FileUtils.forceMkdir(new File(path));
            File upload = new File(path + file.getOriginalFilename());
            file.transferTo(upload);
            user.setAvatar(file.getOriginalFilename());
            IOUtils.closeQuietly(inputStream);
        } catch (IOException ex) {
            System.out.println("Error saving uploaded file");
        }
    }

    userService.update(user);

    redirect.addFlashAttribute("success", "Cp nht profile thnh cng");
    return "redirect:/login";
}