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, String defaultMessage);

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:com.tapas.evidence.fe.controller.UserController.java

@RequestMapping(value = "new", method = RequestMethod.POST)
public String handleRegister(@RequestParam("passwordConfirmation") String passwordConfirmation,
        @Valid @ModelAttribute("user") UserDTO user, BindingResult results, SessionStatus status,
        HttpServletRequest request) {//from  w w w. jav  a  2s .  c  o m
    log.info("Trying to register user: {}", user);
    user.setTenantList(userService.getTenantList());
    String result;

    if (user.getPassword().compareTo(passwordConfirmation) != 0) {
        results.rejectValue("password", "user.password.notsame",
                "Password and confirmation password are not same");
    }

    validateCaptcha(user.getCaptcha(), results, request.getSession().getId(), "screen.register.captcha.error");

    if (!results.hasErrors()) {
        try {
            userService.create(user);
            result = "redirect:/app";
        } catch (TenantAlreadyExists e) {
            log.info("Tenant with name: {} already exists!", user.getTenantName());
            results.rejectValue("tenantName", "tenant.alreadyExists", "Tenant already exists");
            result = "register";
        } catch (UserAlreadyExists e) {
            log.info("User with name: {} already exists!", user.getUserName());
            results.rejectValue("userName", "user.alreadyExists");
            result = "register";
        }
    } else {
        result = "register";
    }
    return result;
}

From source file:com.springsource.greenhouse.signup.SignupHelper.java

/**
 * Signup the person who completed the signup form.
 * Returns true if signup was successful, false if there was an error.
 * Records any errors in the form's BindingResult context for display to the person.
 * An optional SignupCallback may be specified for performing custom processing after successful member signup.
 *//*  w  ww  .j a va 2  s.c om*/
public boolean signup(SignupForm form, BindingResult formBinding, SignupCallback callback) {
    try {
        Account account = createAccount(form.createPerson(), callback);
        gateway.signedUp(account);
        AccountUtils.signin(account);
        if (callback != null) {
            callback.postSignup(account);
        }
        return true;
    } catch (EmailAlreadyOnFileException e) {
        formBinding.rejectValue("email", "account.duplicateEmail", "already on file");
        return false;
    }
}

From source file:org.ng200.openolympus.controller.admin.AdministrativeChangePasswordController.java

@RequestMapping(method = RequestMethod.POST)
public String changePassword(Model model, @Valid final PasswordChangeDto userDto,
        final BindingResult bindingResult, @PathVariable(value = "user") User user) {
    if (bindingResult.hasErrors()) {
        model.addAttribute("hideOldPassword", true);
        model.addAttribute("postUrl", "/admin/user/" + user.getId() + "/changePassword");
        return "user/changePassword";
    }//from  w  w  w . j  av a 2  s.c o  m
    if (!userDto.getPassword().equals(userDto.getPasswordConfirmation())) {
        bindingResult.rejectValue("passwordConfirmation", "",
                "user.changePassword.form.errors.passwordConfirmationDoesntMatch");
    }
    if (bindingResult.hasErrors()) {
        model.addAttribute("hideOldPassword", true);
        model.addAttribute("postUrl", "/admin/user/" + user.getId() + "/changePassword");
        return "user/changePassword";
    }

    user.setPassword(this.passwordEncoder.encode(userDto.getPassword()));
    this.userRepository.save(user);
    return "redirect:/admin/users";
}

From source file:it.jugpadova.controllers.JuggerRegistrationController.java

private void validateJugger(final Jugger jugger, BindingResult result) {
    if (jugger != null) {
        if (jugger.getUser() != null && StringUtils.isNotBlank(jugger.getUser().getUsername())) {
            // check if username is already presents
            String username = jugger.getUser().getUsername();
            if (userDao.findByUsername(username) != null) {
                result.rejectValue("jugger.user.username", "useralreadypresents",
                        "User with username: " + username + " already presents in the database!");
            }/* w w w  .  j a  v a2s.  c o m*/
        }
        if (StringUtils.isNotBlank(jugger.getEmail())) {
            // check if it exists yet a jugger with the same email
            Jugger prevJugger = juggerDao.findByEmail(jugger.getEmail());
            if (prevJugger != null) {
                result.rejectValue("jugger.email", "emailalreadypresent",
                        "An user tried to register with an email that exists yet");
            }
        }
        JUG newJUG = jugger.getJug();
        if (newJUG != null) {
            JUG jug = jugDao.findByName(newJUG.getName());
            if (jug == null) { // it's a new JUG
                final String internalFriendlyName = newJUG.getInternalFriendlyName();
                if (StringUtils.isNotBlank(internalFriendlyName)) {
                    JUG friendlyJug = jugDao.findByInternalFriendlyName(internalFriendlyName);
                    if (friendlyJug != null) {
                        result.rejectValue("jugger.jug.internalFriendlyName", "friendlyNameAlreadyPresent",
                                "An user tried to create a JUG with a friendly name that exists yet");
                    }
                }
            }
        }
    }
}

From source file:no.kantega.kwashc.server.controller.SiteController.java

private String getHeaderValue(Site site, BindingResult result) {
    String header = "";
    try {//w w  w.  java  2s . com
        WebTester tester = new WebTester();
        tester.beginAt(site.getAddress());
        tester.getTestingEngine().gotoRootWindow();
        header = tester.getElementAttributeByXPath("/html/head/meta[@name=\"no.kantega.kwashc\"]", "content");
    } catch (Throwable t) {
        result.rejectValue("address", "",
                "Exception (" + t.getClass().getSimpleName() + ") getting the header value: " + t.getMessage());
    }
    return header;
}

From source file:it.jugpadova.controllers.JuggerEditController.java

private void validateJugger(Jugger jugger, BindingResult result) {
    if (jugger != null) {
        if (StringUtils.isNotBlank(jugger.getEmail())) {
            // check if it exists yet a jugger with the same email
            Jugger prevJugger = juggerDao.findByEmail(jugger.getEmail());
            if (prevJugger != null && !jugger.equals(prevJugger)) {
                result.rejectValue("jugger.email", "emailalreadypresent",
                        "An user tried to register with an email that exists yet");
            }/*from  w ww .  ja  v a2 s .c o m*/
        }
        JUG jug = jugger.getJug();
        if (jug != null) {
            final String internalFriendlyName = jug.getInternalFriendlyName();
            if (StringUtils.isNotBlank(internalFriendlyName)) {
                JUG friendlyJug = jugDao.findByInternalFriendlyName(internalFriendlyName);
                if (friendlyJug != null && !friendlyJug.equals(jug)) {
                    result.rejectValue("jugger.jug.internalFriendlyName", "friendlyNameAlreadyPresent",
                            "An user tried to create a JUG with a friendly name that exists yet");
                }
            }
        }
    }
}

From source file:org.ng200.openolympus.controller.user.ChangePasswordController.java

@RequestMapping(method = RequestMethod.POST)
public String changePassword(Model model, @Valid final PasswordChangeDto userDto,
        final BindingResult bindingResult, final Principal principal) {
    if (bindingResult.hasErrors()) {
        model.addAttribute("postUrl", "/user/changePassword");
        model.addAttribute("hideOldPassword", false);
        return "user/changePassword";
    }/*from  w  w  w. j a  va 2  s  .co m*/
    final User user = this.userRepository.findByUsername(principal.getName());
    if (!this.passwordEncoder.matches(userDto.getExistingPassword(), user.getPassword())) {
        bindingResult.rejectValue("existingPassword", "",
                "user.changePassword.form.errors.existingPasswordDoesntMatch");
    }
    if (!userDto.getPassword().equals(userDto.getPasswordConfirmation())) {
        bindingResult.rejectValue("passwordConfirmation", "",
                "user.changePassword.form.errors.passwordConfirmationDoesntMatch");
    }
    if (bindingResult.hasErrors()) {
        model.addAttribute("hideOldPassword", false);
        model.addAttribute("postUrl", "/user/changePassword");
        return "user/changePassword";
    }

    user.setPassword(this.passwordEncoder.encode(userDto.getPassword()));
    this.userRepository.save(user);
    return "redirect:/user";
}

From source file:org.axonframework.samples.trader.webui.companies.CompanyController.java

@RequestMapping(value = "/buy/{companyId}", method = RequestMethod.POST)
public String buy(@ModelAttribute("order") @Valid BuyOrder order, BindingResult bindingResult, Model model) {
    if (!bindingResult.hasErrors()) {

        OrderBookEntry bookEntry = obtainOrderBookForCompany(order.getCompanyId());
        PortfolioEntry portfolioEntry = obtainPortfolioForUser();

        if (portfolioEntry.obtainMoneyToSpend() < order.getTradeCount() * order.getItemPrice()) {
            bindingResult.rejectValue("tradeCount", "error.order.buy.notenoughmoney",
                    "Not enough cash to spend to buy the items for the price you want");
            addPortfolioMoneyInfoToModel(portfolioEntry, model);
            return "company/buy";
        }//w ww.ja  v  a2 s  .  c o m

        StartBuyTransactionCommand command = new StartBuyTransactionCommand(new TransactionId(),
                new OrderBookId(bookEntry.getIdentifier()), new PortfolioId(portfolioEntry.getIdentifier()),
                order.getTradeCount(), order.getItemPrice());
        commandBus.dispatch(new GenericCommandMessage<StartBuyTransactionCommand>(command));
        return "redirect:/company/{companyId}";
    }

    addPortfolioMoneyInfoToModel(model);
    return "company/buy";
}

From source file:com.github.dbourdette.otto.web.controller.sources.SourcesController.java

@RequestMapping(value = "/sources/{name}/schedule", method = RequestMethod.POST)
public String schedule(@PathVariable String name, @Valid @ModelAttribute("form") MailSchedule form,
        BindingResult result, Model model) {
    if (!result.hasErrors()) {
        if (StringUtils.isEmpty(form.getReport())) {
            result.rejectValue("report", "value.notNull", "Can't be null");
        }/* w w w  . j av a  2s.  c  o  m*/

        if (form.getPeriod() == null) {
            result.rejectValue("period", "value.notNull", "Can't be null");
        }
    }

    if (result.hasErrors()) {
        model.addAttribute("reports", ReportConfigs.forSource(Source.findByName(name)).getReportConfigs());

        return "sources/schedule/edit";
    }

    form.setSourceName(name);

    sourceSchedules.save(form);

    return "redirect:/sources/{name}/configuration";
}

From source file:org.axonframework.samples.trader.webui.companies.CompanyController.java

@RequestMapping(value = "/sell/{companyId}", method = RequestMethod.POST)
public String sell(@ModelAttribute("order") @Valid SellOrder order, BindingResult bindingResult, Model model) {
    if (!bindingResult.hasErrors()) {
        OrderBookEntry bookEntry = obtainOrderBookForCompany(order.getCompanyId());
        PortfolioEntry portfolioEntry = obtainPortfolioForUser();

        if (portfolioEntry.obtainAmountOfAvailableItemsFor(bookEntry.getIdentifier()) < order.getTradeCount()) {
            bindingResult.rejectValue("tradeCount", "error.order.sell.tomanyitems",
                    "Not enough items available to create sell order.");
            addPortfolioItemInfoToModel(order.getCompanyId(), model);
            return "company/sell";
        }//  w w w  . j av a2  s .co  m

        StartSellTransactionCommand command = new StartSellTransactionCommand(new TransactionId(),
                new OrderBookId(bookEntry.getIdentifier()), new PortfolioId(portfolioEntry.getIdentifier()),
                order.getTradeCount(), order.getItemPrice());

        commandBus.dispatch(new GenericCommandMessage<StartSellTransactionCommand>(command));

        return "redirect:/company/{companyId}";
    }

    addPortfolioItemInfoToModel(order.getCompanyId(), model);
    return "company/sell";
}