Example usage for org.springframework.validation BindingResult rejectValue

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

Introduction

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

Prototype

void rejectValue(@Nullable String field, String errorCode);

Source Link

Document

Register a field error for the specified field of the current object (respecting the current nested path, if any), using the given error description.

Usage

From source file:cz.muni.fi.editor.webapp.controllers.OrganizationController.java

@RequestMapping(value = "/", method = RequestMethod.POST)
public String createOrganization(@ModelAttribute("organizationForm") @Valid OrganizationForm organizationForm,
        BindingResult bindingResult, Model model, RedirectAttributes ra) {
    if (bindingResult.hasErrors()) {
        return "organization.list";
    } else {/*from ww  w.  j  a v  a2s  .c om*/
        try {
            organizationService.create(mapper.map(organizationForm, OrganizationDTO.class));

            return "redirect:/auth/organization/";
        } catch (FieldException ex) {
            log.warn(ex);
            bindingResult.rejectValue(ex.getField(), ex.getMessage());

            return "organization.list";
        }

    }
}

From source file:org.wallride.web.controller.admin.article.ArticleCreateController.java

@RequestMapping(method = RequestMethod.POST, params = "draft")
public @ResponseBody DomainObjectSavedModel saveAsDraft(@PathVariable String language,
        @Validated @ModelAttribute("form") ArticleCreateForm form, BindingResult errors,
        AuthorizedUser authorizedUser) throws BindException {
    if (errors.hasErrors()) {
        for (ObjectError error : errors.getAllErrors()) {
            if (!"validation.NotNull".equals(error.getCode())) {
                throw new BindException(errors);
            }/*from   w  ww .  jav a  2 s.  c  om*/
        }
    }

    Article article = null;
    try {
        article = articleService.createArticle(form.buildArticleCreateRequest(), Post.Status.DRAFT,
                authorizedUser);
    } catch (EmptyCodeException e) {
        errors.rejectValue("code", "NotNull");
    } catch (DuplicateCodeException e) {
        errors.rejectValue("code", "NotDuplicate");
    }
    if (errors.hasErrors()) {
        logger.debug("Errors: {}", errors);
        throw new BindException(errors);
    }

    return new DomainObjectSavedModel<>(article);
}

From source file:org.wallride.web.controller.admin.page.PageCreateController.java

@RequestMapping(method = RequestMethod.POST, params = "draft")
public @ResponseBody DomainObjectSavedModel saveAsDraft(@PathVariable String language,
        @Validated @ModelAttribute("form") PageCreateForm form, BindingResult errors,
        AuthorizedUser authorizedUser, RedirectAttributes redirectAttributes) throws BindException {
    if (errors.hasErrors()) {
        for (ObjectError error : errors.getAllErrors()) {
            if (!"validation.NotNull".equals(error.getCode())) {
                throw new BindException(errors);
            }/*from   ww  w. ja v  a 2s  .  c  om*/
        }
    }

    Page page = null;
    try {
        page = pageService.createPage(form.buildPageCreateRequest(), Post.Status.DRAFT, authorizedUser);
    } catch (EmptyCodeException e) {
        errors.rejectValue("code", "NotNull");
    } catch (DuplicateCodeException e) {
        errors.rejectValue("code", "NotDuplicate");
    }
    if (errors.hasErrors()) {
        logger.debug("Errors: {}", errors);
        throw new BindException(errors);
    }

    return new DomainObjectSavedModel<>(page);
}

From source file:org.wallride.web.controller.guest.user.PasswordResetController.java

@RequestMapping(method = RequestMethod.POST)
public String token(@Validated @ModelAttribute(FORM_MODEL_KEY) PasswordResetForm form, BindingResult errors,
        BlogLanguage blogLanguage, RedirectAttributes redirectAttributes) {
    redirectAttributes.addFlashAttribute(FORM_MODEL_KEY, form);
    redirectAttributes.addFlashAttribute(ERRORS_MODEL_KEY, errors);

    if (errors.hasFieldErrors("email")) {
        return "redirect:/password-reset";
    }/* ww w . j a va 2 s.  co  m*/

    PasswordResetTokenCreateRequest request = form.toPasswordResetTokenCreateRequest(blogLanguage);
    PasswordResetToken passwordResetToken;
    try {
        passwordResetToken = userService.createPasswordResetToken(request);
    } catch (EmailNotFoundException e) {
        errors.rejectValue("email", "UsedEmail");
        return "redirect:/password-reset";
    }

    redirectAttributes.getFlashAttributes().clear();
    redirectAttributes.addFlashAttribute("passwordResetToken", passwordResetToken);
    return "redirect:/password-reset?step.token";
}

From source file:edu.unlv.kilo.web.ChartingController.java

@RequestMapping(method = RequestMethod.POST)
public String post(@Valid ChartingForm form, BindingResult result, Model model, HttpServletRequest request) {
    // Returns the form with errors found from the @ checks
    if (result.hasErrors()) {
        return createForm(model, form);
    }/*from  w w  w. ja v a  2  s  .  c o m*/

    Calendar startDate = form.getStartDate(); // Gets the start date from the user
    Calendar endDate = form.getEndDate(); // Gets the end date from the user

    // Have to make sure the begin date is actually before the end date
    // If not, throw an error
    if (startDate.after(endDate)) {
        result.rejectValue("startDate", "start_date_after_end");
        return createForm(model, form);
        //result.rejectValue("startDate", "start_after_end", "The start date must be before the end date.");
    }

    int interval = form.getDay_Interval(); // Gets the interval in days from the user

    // Send the data to projecting and receive the points to plot
    //List<MoneyValue> data_Points = Projection.getGraphData(startDate, endDate, interval);

    /*------------TEST CASE------------------------------------------*/
    List<MoneyValue> data_Points = new ArrayList<MoneyValue>();
    data_Points.clear();
    for (long j = 0; j < 10; j++) {
        MoneyValue abc = new MoneyValue();
        abc.setAmount(j);
        data_Points.add(abc);
    }
    /*------------TEST CASE------------------------------------------*/

    // This sets up the start date and end date to be able
    // to be printed in a nice default format.
    SimpleDateFormat nice_String = new SimpleDateFormat("MM/dd/yyyy");
    String begin_Print = null;
    String end_Print = null;
    begin_Print = nice_String.format(startDate.getTime());
    end_Print = nice_String.format(endDate.getTime());

    /*-------------GRAPHING STARTS HERE-------------*/
    int number_of_points = data_Points.size();

    // Holds the points for graphing.
    // Library dictates it must be a double
    double[] points = new double[number_of_points];

    // These values are set so they're sure to be changed
    double min_Value = 1000000; // The minimum Money amount in the list
    double max_Value = 0; // The maximum Money amount in the list

    // Put the Money amounts into the array and check for updated
    // minimum and maximum values.
    for (int i = 0; i < number_of_points; i++) {
        points[i] = (double) data_Points.get(i).getAmount();
        if (min_Value > points[i]) {
            min_Value = points[i];
        }
        if (max_Value < points[i]) {
            max_Value = points[i];
        }
    }

    //Line charting_Line = Plots.newLine(Data.newData(points), RED, "Item");
    Line charting_Line = Plots.newLine(DataUtil.scaleWithinRange(min_Value, max_Value, points), RED, "Item");
    charting_Line.setLineStyle(LineStyle.newLineStyle(3, 1, 0));
    charting_Line.addShapeMarkers(Shape.CIRCLE, Color.AQUAMARINE, 8);

    // Defining the chart
    LineChart chart = GCharts.newLineChart(charting_Line);
    chart.setSize(550, 450);
    chart.setTitle("Budgeting Line Chart", MAROON, 14);
    chart.setGrid(number_of_points, number_of_points, 3, 2);

    // Defining the axis information and styles
    AxisStyle axisStyle = AxisStyle.newAxisStyle(BLACK, 12, AxisTextAlignment.CENTER);
    AxisLabels xAxis = AxisLabelsFactory.newAxisLabels(begin_Print, "Dates", end_Print);
    xAxis.setAxisStyle(axisStyle);
    AxisLabels yAxis = AxisLabelsFactory.newNumericAxisLabels(min_Value, max_Value);
    yAxis.setAxisStyle(axisStyle);

    // Adding axis information to the chart
    chart.addXAxisLabels(xAxis);
    chart.addYAxisLabels(yAxis);

    // Defining the background color
    chart.setBackgroundFill(Fills.newSolidFill(LIGHTBLUE));

    // The image url to be sent to the jspx
    String url = chart.toURLString();

    // Setting the "url" variable for the jspx
    model.addAttribute("url", chart.toURLString());

    return "charting/graph";
}

From source file:com.sf.springsecurityregistration1.web.controllers.RegistrationController.java

/**
 * Method used to check and persist a new user data.
 *
 * @param accountDto user to be persisted
 * @param result used to detect errors in form
 * @param request for future code/*from w ww .j  a v a  2s  .c  o  m*/
 * @param errors for future code
 * @return model of the success view or that of the registration page
 */
@RequestMapping(value = "/user/**/registration", method = RequestMethod.POST)
public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid Users accountDto, BindingResult result,
        WebRequest request, Errors errors) {
    System.out.println("/user/registration");
    Users registered = new Users();
    //        accountDto.setUsername(changeEncoding(accountDto.getUsername(),
    //                pageEncoding, dbEncoding));
    if (!result.hasErrors()) {
        System.out.println("!result.hasErrors()");
        registered = createUserAccount(accountDto, result);
    }
    if (registered == null) {
        System.out.println("registered == null");
        result.rejectValue("username", "message.regError");
    }
    if (result.hasErrors()) {
        System.out.println("result.hasErrors()");
        ModelAndView model = new ModelAndView("registration");
        model.addObject("user", accountDto);
        return model;
    } else {
        ModelAndView model = new ModelAndView("successRegister");
        model.addObject("user", accountDto);
        return model;
    }
}

From source file:com.exxonmobile.ace.hybris.storefront.controllers.pages.BudgetManagementPageController.java

@RequestMapping(value = "/add", method = RequestMethod.POST)
@RequireHardLogIn/*from   w w  w . j  a  v  a 2s  .  c  om*/
public String addNewBudget(@Valid final B2BBudgetForm b2BBudgetForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectModel)
        throws CMSItemNotFoundException, ParseException {
    b2BBudgetFormValidator.validate(b2BBudgetForm, bindingResult);
    if (bindingResult.hasFieldErrors()) {
        model.addAttribute(b2BBudgetForm);
        return getAddBudgetPage(model);
    }
    if (checkEndDateIsBeforeStartDateForBudget(b2BBudgetForm)) {
        model.addAttribute(b2BBudgetForm);
        bindingResult.rejectValue("endDate", "text.company.budget.endDateLesser.error.title");
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return getAddBudgetPage(model);
    }
    final B2BBudgetData b2BBudgetData = populateB2BBudgetDataFromForm(b2BBudgetForm);
    try {
        b2bCommerceBudgetFacade.addBudget(b2BBudgetData);
    } catch (final Exception e) {
        LOG.warn("Exception while saving the budget details " + e);
        model.addAttribute(b2BBudgetForm);
        bindingResult.rejectValue("code", "text.company.budget.code.exists.error.title");
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return getAddBudgetPage(model);
    }
    storeCmsPageInModel(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManageBudgetsBreadCrumbs();
    breadcrumbs.add(new Breadcrumb("/my-company/organization-management/manage-budgets/update",
            getMessageSource().getMessage("text.company.budget.editPage", null,
                    getI18nService().getCurrentLocale()),
            null));
    model.addAttribute("breadcrumbs", breadcrumbs);
    GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
            "text.confirmation.budget.created");
    return String.format(REDIRECT_TO_BUDGET_DETAILS, urlEncode(b2BBudgetData.getCode()));
}

From source file:com.jnj.b2b.storefront.controllers.pages.BudgetManagementPageController.java

@RequestMapping(value = "/add", method = RequestMethod.POST)
@RequireHardLogIn/*from w w w .ja va2s  .c  o  m*/
public String addNewBudget(@Valid final B2BBudgetForm b2BBudgetForm, final BindingResult bindingResult,
        final Model model, final RedirectAttributes redirectModel)
        throws CMSItemNotFoundException, ParseException {
    b2BBudgetFormValidator.validate(b2BBudgetForm, bindingResult);
    if (bindingResult.hasFieldErrors()) {
        model.addAttribute(b2BBudgetForm);
        return getAddBudgetPage(model);
    }
    if (checkEndDateIsBeforeStartDateForBudget(b2BBudgetForm)) {
        model.addAttribute(b2BBudgetForm);
        bindingResult.rejectValue("endDate", "text.company.budget.endDateLesser.error.title");
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return getAddBudgetPage(model);
    }
    final B2BBudgetData b2BBudgetData = populateB2BBudgetDataFromForm(b2BBudgetForm);
    try {
        budgetFacade.addBudget(b2BBudgetData);
    } catch (final Exception e) {
        LOG.warn("Exception while saving the budget details " + e);
        model.addAttribute(b2BBudgetForm);
        bindingResult.rejectValue("code", "text.company.budget.code.exists.error.title");
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return getAddBudgetPage(model);
    }
    storeCmsPageInModel(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManageBudgetsBreadCrumbs();
    breadcrumbs.add(new Breadcrumb("/my-company/organization-management/manage-budgets/update",
            getMessageSource().getMessage("text.company.budget.editPage", null,
                    getI18nService().getCurrentLocale()),
            null));
    model.addAttribute("breadcrumbs", breadcrumbs);
    GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
            "text.confirmation.budget.created");
    return String.format(REDIRECT_TO_BUDGET_DETAILS, urlEncode(b2BBudgetData.getCode()));
}

From source file:com.trenako.web.controllers.admin.AdminScalesController.java

/**
 * It creates a new {@code Scale} using the posted form values.
 * <p/>/*from  w w  w .  ja  va  2 s.  c  o m*/
 * <p>
 * <pre><blockquote>
 * {@code POST /admin/scales}
 * </blockquote></pre>
 * </p>
 *
 * @param scale         the {@code Scale} to be added
 * @param bindingResult the validation results
 * @param model         the model
 * @param redirectAtts  the redirect attributes
 * @return the view name
 */
@RequestMapping(method = RequestMethod.POST)
public String create(@Valid @ModelAttribute Scale scale, BindingResult bindingResult, ModelMap model,
        RedirectAttributes redirectAtts) {

    if (bindingResult.hasErrors()) {
        LogUtils.logValidationErrors(log, bindingResult);
        model.addAttribute(scale);
        return "scale/new";
    }

    try {
        service.save(scale);
        SCALE_CREATED_MSG.appendToRedirect(redirectAtts);
        return "redirect:/admin/scales";
    } catch (DuplicateKeyException dke) {
        LogUtils.logException(log, dke);
        bindingResult.rejectValue("name", "scale.name.already.used");
    } catch (DataAccessException dae) {
        LogUtils.logException(log, dae);
        SCALE_DB_ERROR_MSG.appendToModel(model);
    }

    model.addAttribute(scale);
    return "scale/new";
}

From source file:com.exxonmobile.ace.hybris.storefront.controllers.pages.BudgetManagementPageController.java

@RequestMapping(value = "/update", method = RequestMethod.POST)
@RequireHardLogIn/*  w w  w  .j  a  v  a  2s . c o m*/
public String updateBudgetsDetails(@RequestParam("budgetCode") final String budgetCode,
        @Valid final B2BBudgetForm b2BBudgetForm, final BindingResult bindingResult, final Model model,
        final RedirectAttributes redirectModel) throws CMSItemNotFoundException, ParseException {
    b2BBudgetFormValidator.validate(b2BBudgetForm, bindingResult);
    if (bindingResult.hasErrors()) {
        model.addAttribute(b2BBudgetForm);
        return editBudgetsDetails(b2BBudgetForm.getOriginalCode(), model);
    }
    if (checkEndDateIsBeforeStartDateForBudget(b2BBudgetForm)) {
        model.addAttribute(b2BBudgetForm);
        bindingResult.rejectValue("endDate", "text.company.budget.endDateLesser.error.title");
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return editBudgetsDetails(b2BBudgetForm.getOriginalCode(), model);
    }
    final B2BBudgetData b2BBudgetData = populateB2BBudgetDataFromForm(b2BBudgetForm);
    try {
        b2bCommerceBudgetFacade.updateBudgetDetails(b2BBudgetData);

    } catch (final Exception e) {
        LOG.warn("Exception while saving the budget details " + e);
        model.addAttribute(b2BBudgetForm);
        GlobalMessages.addErrorMessage(model, "form.global.error");
        return editBudgetsDetails(b2BBudgetForm.getOriginalCode(), model);
    }
    storeCmsPageInModel(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    setUpMetaDataForContentPage(model, getContentPageForLabelOrId(ORGANIZATION_MANAGEMENT_CMS_PAGE));
    final List<Breadcrumb> breadcrumbs = myCompanyBreadcrumbBuilder.createManageBudgetsBreadCrumbs();
    breadcrumbs.add(new Breadcrumb("/my-company/organization-management/manage-budgets/update",
            getMessageSource().getMessage("text.company.budget.editPage", null,
                    getI18nService().getCurrentLocale()),
            null));
    model.addAttribute("breadcrumbs", breadcrumbs);
    GlobalMessages.addFlashMessage(redirectModel, GlobalMessages.CONF_MESSAGES_HOLDER,
            "text.confirmation.budget.updated");
    return String.format(REDIRECT_TO_BUDGET_DETAILS, urlEncode(b2BBudgetData.getCode()));
}