Example usage for org.springframework.validation BindingResult reject

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

Introduction

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

Prototype

void reject(String errorCode);

Source Link

Document

Register a global error for the entire target object, using the given error description.

Usage

From source file:cn.guoyukun.spring.jpa.plugin.web.controller.BaseTreeableController.java

@RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
public String deleteSelfAndChildren(Model model, @ModelAttribute("m") M m, BindingResult result,
        RedirectAttributes redirectAttributes) {

    if (permissionList != null) {
        permissionList.assertHasDeletePermission();
    }/* w w w  .ja va 2 s . c  o m*/

    if (m.isRoot()) {
        result.reject("???");
        return deleteForm(m, model);
    }

    baseService.deleteSelfAndChild(m);
    redirectAttributes.addFlashAttribute(Constants.MESSAGE, "?");
    return redirectToUrl(viewName("success"));
}

From source file:fi.koku.kks.controller.CreateCollectionController.java

@ActionMapping(params = "action=createCollection")
public void create(PortletSession session, @ModelAttribute(value = "child") Person child, Creation creation,
        BindingResult bindingResult, ActionResponse response, SessionStatus sessionStatus) {

    LOG.debug("create collection");

    creation.validate(creation, bindingResult);
    if (!bindingResult.hasErrors()) {

        Creatable a = Creatable.create(creation.getField());
        String name = "".equals(creation.getName()) ? a.getName() : creation.getName();
        String id = kksService.createKksCollection(name, a.getId(), child.getPic(),
                Utils.getPicFromSession(session));

        if (id == null) {
            bindingResult.reject("collection.create.failed");
        }/*from w w w.j av  a  2  s  . com*/

        creation.setField("");
        creation.setName("");
        response.setRenderParameter("action", "showChild");
        response.setRenderParameter("pic", child.getPic());

        if (id != null) {
            sessionStatus.setComplete();
        }
    } else {
        response.setRenderParameter("action", "showChild");
        response.setRenderParameter("pic", child.getPic());
    }
}

From source file:com.hadoopvietnam.controller.member.ChangePasswordController.java

@PreAuthorize("isAuthenticated()")
@RequestMapping(method = { org.springframework.web.bind.annotation.RequestMethod.POST })
public String changePassword(@ModelAttribute("changePasswordForm") ChangePasswordForm form,
        BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
    this.validator.validate(form, bindingResult);
    if (bindingResult.hasErrors()) {
        uiModel.addAttribute("changePasswordForm", form);
        return "user/changepassword";
    }// w  w w .  j a  v a 2  s  .c  om
    try {
        this.accountService.changePassword(getUsername(),
                this.passwordEncoder.encodePassword(form.getNewPassword(), null));
        return "user/successchangepassword";
    } catch (Exception ex) {
        logger.error("Change password for user " + getUsername() + " error.", ex);
        bindingResult.reject("changepassword.error");
        uiModel.addAttribute("changePasswordForm", new ChangePasswordForm());
    }
    return "user/changepassword";
}

From source file:alfio.controller.form.PaymentForm.java

public void validate(BindingResult bindingResult, TotalPrice reservationCost, Event event,
        List<TicketFieldConfiguration> fieldConf) {

    List<PaymentProxy> allowedPaymentMethods = event.getAllowedPaymentProxies();

    Optional<PaymentProxy> paymentProxyOptional = Optional.ofNullable(paymentMethod);
    PaymentProxy paymentProxy = paymentProxyOptional.filter(allowedPaymentMethods::contains)
            .orElse(PaymentProxy.STRIPE);
    boolean priceGreaterThanZero = reservationCost.getPriceWithVAT() > 0;
    boolean multiplePaymentMethods = allowedPaymentMethods.size() > 1;
    if (multiplePaymentMethods && priceGreaterThanZero && !paymentProxyOptional.isPresent()) {
        bindingResult.reject(ErrorsCode.STEP_2_MISSING_PAYMENT_METHOD);
    } else if (priceGreaterThanZero
            && (paymentProxy == PaymentProxy.STRIPE && StringUtils.isBlank(stripeToken))) {
        bindingResult.reject(ErrorsCode.STEP_2_MISSING_STRIPE_TOKEN);
    }/*from w ww.j a v a 2  s  . co  m*/

    if (Objects.isNull(termAndConditionsAccepted) || !termAndConditionsAccepted) {
        bindingResult.reject(ErrorsCode.STEP_2_TERMS_NOT_ACCEPTED);
    }

    email = StringUtils.trim(email);

    fullName = StringUtils.trim(fullName);
    firstName = StringUtils.trim(firstName);
    lastName = StringUtils.trim(lastName);

    billingAddress = StringUtils.trim(billingAddress);

    ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "email", ErrorsCode.STEP_2_EMPTY_EMAIL);
    rejectIfOverLength(bindingResult, "email", ErrorsCode.STEP_2_MAX_LENGTH_EMAIL, email, 255);

    if (event.mustUseFirstAndLastName()) {
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "firstName",
                ErrorsCode.STEP_2_EMPTY_FIRSTNAME);
        rejectIfOverLength(bindingResult, "firstName", ErrorsCode.STEP_2_MAX_LENGTH_FIRSTNAME, fullName, 255);
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "lastName", ErrorsCode.STEP_2_EMPTY_LASTNAME);
        rejectIfOverLength(bindingResult, "lastName", ErrorsCode.STEP_2_MAX_LENGTH_LASTNAME, fullName, 255);
    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "fullName", ErrorsCode.STEP_2_EMPTY_FULLNAME);
        rejectIfOverLength(bindingResult, "fullName", ErrorsCode.STEP_2_MAX_LENGTH_FULLNAME, fullName, 255);
    }

    rejectIfOverLength(bindingResult, "billingAddress", ErrorsCode.STEP_2_MAX_LENGTH_BILLING_ADDRESS,
            billingAddress, 450);

    if (email != null && !email.contains("@") && !bindingResult.hasFieldErrors("email")) {
        bindingResult.rejectValue("email", ErrorsCode.STEP_2_INVALID_EMAIL);
    }

    if (hasPaypalTokens() && !PaypalManager.isValidHMAC(new CustomerName(fullName, firstName, lastName, event),
            email, billingAddress, hmac, event)) {
        bindingResult.reject(ErrorsCode.STEP_2_INVALID_HMAC);
    }

    if (!postponeAssignment) {
        boolean success = Optional.ofNullable(tickets).filter(m -> !m.isEmpty()).map(m -> m.entrySet().stream()
                .map(e -> Validator.validateTicketAssignment(e.getValue(), fieldConf, Optional.empty(), event)))
                .filter(s -> s.allMatch(ValidationResult::isSuccess)).isPresent();
        if (!success) {
            bindingResult.reject(ErrorsCode.STEP_2_MISSING_ATTENDEE_DATA);
        }
    }
}

From source file:org.openmrs.module.cohort.web.controller.EditCohortController.java

@RequestMapping(value = "/module/cohort/editCohortRole.form", method = RequestMethod.POST)
public void manageEditRoles1(ModelMap model, HttpSession httpSession, HttpServletRequest request,
        @RequestParam("croleid") Integer id, @ModelAttribute("cohortrole") CohortRole cohort,
        BindingResult errors) {
    if (!Context.isAuthenticated()) {
        errors.reject("Required");
    } else if (request.getParameter("name").equals("") || request.getParameter("format").equals("")) {
        errors.reject("Fields required");
    } else {//from w w w  .  ja v a  2 s  . c om
        CohortService service1 = Context.getService(CohortService.class);
        List<CohortRole> cohortRolesPresent = service1.findCohortRole(id);
        for (int a = 0; a < cohortRolesPresent.size(); a++) {
            cohort = cohortRolesPresent.get(a);
        }
        if ("Edit Role".equals(request.getParameter("Edit Role"))) {
            List<CohortRole> roles = service1.findCohortRole(id);
            List<String> cohortTypeToSetInView = new ArrayList<String>();
            //Someone coded everything as a list. The list is gonna return only 1 element. Why would anyone do that -.-
            for (CohortRole role : roles) {
                role.setName(request.getParameter("name"));
                for (CohortType cohortType : service1.findCohortType(request.getParameter("format"))) {
                    role.setCohortType(cohortType);
                    //set the correct type
                    cohortTypeToSetInView.add(cohortType.getName());
                }
            }
            //Find all the other types to choose from
            List<CohortType> list1 = service1.getAllCohortTypes();
            for (int i = 0; i < list1.size(); i++) {
                CohortType c = list1.get(i);
                if (!cohortTypeToSetInView.contains(c.getName())) {
                    cohortTypeToSetInView.add(c.getName());
                }
            }
            //Set this in the dropdown
            model.addAttribute("formats", cohortTypeToSetInView);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Edit Success");
        }

        if ("delete".equals(request.getParameter("delete"))) {
            service1.purgeCohortRole(cohort);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "delete success");
        }
    }
}

From source file:org.wallride.web.controller.admin.analytics.GoogleAnalyticsUpdateController.java

@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";
    }/* w  w  w  .java 2 s. co  m*/

    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";
}

From source file:org.openmrs.module.personalization.web.controller.personalizationManageController.java

@RequestMapping(value = "/module/personalization/manage.form", method = RequestMethod.POST)
public personalization submitPersonalization(WebRequest request, HttpSession httpSession, ModelMap model,
        @RequestParam(required = false, value = "action") String action,
        @RequestParam(required = false, value = "breakfast") String breakfast,
        @RequestParam(required = false, value = "evening") String evening,
        @RequestParam(required = false, value = "fasting") String fasting,
        @RequestParam(required = false, value = "lunch") String lunch,
        @RequestParam(required = false, value = "breakfastAlarm") String breakfastAlarm,
        @RequestParam(required = false, value = "eveningAlarm") String eveningAlarm,
        @RequestParam(required = false, value = "lunchAlarm") String lunchAlarm,
        @RequestParam(required = false, value = "fastingAlarm") String fastingAlarm,
        @RequestParam(required = false, value = "day") String day,
        @RequestParam(required = false, value = "time") String time,
        @RequestParam(required = false, value = "dayAlarm") String dayAlarm,
        @RequestParam(required = false, value = "day1") String day1,
        @RequestParam(required = false, value = "day2") String day2,
        @RequestParam(required = true, value = "patientId") String patientId,
        @ModelAttribute("personalization") personalization personalization, BindingResult errors) {

    MessageSourceService mss = Context.getMessageSourceService();
    personalizationService personalizationService = Context.getService(personalizationService.class);
    personalization per = personalizationService.getPersonalizationByUuid(patientId);
    if (per == null)
        per = new personalization();
    per.setEvening(evening);//  w w  w  .ja v a2 s  .  c  o  m
    per.setBreakfast(breakfast);
    per.setLunch(lunch);
    per.setFasting(fasting);
    per.setBreakfastAlarm(breakfastAlarm);
    per.setLunchAlarm(lunchAlarm);
    per.setEveningAlarm(eveningAlarm);
    per.setFastingAlarm(fastingAlarm);
    per.setUuid(patientId);
    per.setDay(day);
    per.setTime(time);
    per.setDayAlarm(dayAlarm);
    per.setDay1(day1);
    per.setDay2(day2);

    log.warn("Action: " + action);
    if (!Context.isAuthenticated()) {
        log.warn("athu required" + action);
        errors.reject("personalization.auth.required");
    } else if (mss.getMessage("personalization.purgePersonalization").equals(action)) {
        try {
            personalizationService.purgePersonalization(per);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "personalization.delete.success");
            log.warn("Action1: " + action);
            return per;
            //                return "redirect:personalizationList.list";
        } catch (Exception ex) {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "personalization.delete.failure");
            log.error("Failed to delete personalization", ex);
            log.warn("Action2: " + action);
            return per;
            //                return "redirect:personalizationForm.form?personalizationId=" + request.getParameter("personalizationId");
        }
    } else {
        log.warn(per.getPersonalizationId() + "---" + per.getBreakfast());
        personalizationService.savePersonalization(per);
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "personalization.saved");
        log.warn("Action3: " + action);
    }
    return per;
    //        return "redirect:personalizationList.list";
}