Example usage for org.springframework.validation BindingResult addError

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

Introduction

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

Prototype

void addError(ObjectError error);

Source Link

Document

Add a custom ObjectError or FieldError to the errors list.

Usage

From source file:de.rahn.finances.server.web.ui.SecuritiesController.java

/**
 * Speichere das Wertpapier./*from w ww. ja va  2  s.co m*/
 *
 * @param security das genderte Wertpapier
 * @return die nchste anzuzeigende View
 */
@RequestMapping(value = "/security", method = POST)
public String security(@Valid @ModelAttribute("security") Security security, BindingResult bindingResult) {
    LOGGER.info("Methode aufgerufen: security({})", security);

    if (bindingResult.hasErrors()) {
        return "security";
    }

    try {
        security = service.save(security);
    } catch (Exception exception) {
        LOGGER.error("Fehler beim Speichern eines Wertpapiers", exception);
        bindingResult.addError(new ObjectError("security", exception.toString()));
        return "security";
    }

    return "redirect:/securities";
}

From source file:org.socialsignin.springsocial.security.signup.AbstractSignUpController.java

private String signUpUser(ServletWebRequest request, P springSocialSecurityProfile, BindingResult errors) {
    String userName = springSocialSecurityProfile.getUserName();
    if (!isUserNameValid(userName, errors)) {
        return null;
    }// w  w  w . j  a v a2s . com
    customValidation(springSocialSecurityProfile, errors);

    if (errors.hasErrors())
        return null;

    if (!signUpService.isUserIdAvailable(userName)) {
        errors.addError(new FieldError("signUpForm", "userName",
                "Sorry, the username '" + userName + "' is not available"));
        return null;
    }

    try {
        signUpService.signUpUserAndCompleteConnection(springSocialSecurityProfile, request);
        return springSocialSecurityProfile.getUserName();
    } catch (UsernameAlreadyExistsException e) {
        errors.addError(new FieldError("signUpForm", "userName",
                "Sorry, the username '" + userName + "' is not available"));
        return null;
    }
}

From source file:org.jblogcms.core.blog.controller.EditBlogController.java

/**
 * Returns saved blog, if exceptions occurs translates them into {@link org.springframework.validation.FieldError}s
 * and adds those errors to the {@code BindingResult} object
 *
 * @param blogForm the new blog//from   ww w.ja v a2  s  .  c o  m
 * @param result   the {@code BindingResult} object
 * @return the saved blog
 */
private Blog editBlog(Blog blogForm, BindingResult result) {
    Blog blog = null;
    try {
        blog = blogService.editBlog(blogForm);

    } catch (DuplicateBlogNameException e) {

        String errorCode = messageSource.getMessage(e.getLocalMessage(), null, null);
        FieldError error = new FieldError("blog", "name", blogForm.getName(), false, new String[] { errorCode },
                new Object[] {}, errorCode);
        result.addError(error);

    } catch (DuplicateBlogUrlNameException e) {

        String errorCode = messageSource.getMessage(e.getLocalMessage(), null, null);
        FieldError error = new FieldError("blog", "urlName", blogForm.getUrlName(), false,
                new String[] { errorCode }, new Object[] {}, errorCode);
        result.addError(error);

    }
    return blog;
}

From source file:com.sjsu.bikelet.web.TenantLicensePolicyController.java

@RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String create(@Valid TenantLicensePolicy tenantLicensePolicy, BindingResult bindingResult, Model uiModel,
        HttpServletRequest httpServletRequest) {
    validateDate(bindingResult, tenantLicensePolicy);

    if (bindingResult.hasErrors()) {
        populateEditForm(uiModel, tenantLicensePolicy);
        return "tenantlicensepolicys/create";
    }/*from  ww w . jav  a  2 s.c  o  m*/
    uiModel.asMap().clear();

    try {
        tenantLicensePolicyService.saveTenantLicensePolicy(tenantLicensePolicy);
    } catch (BikeletValidationException e) {
        bindingResult.addError(new ObjectError("tenantLicensePolicy", e.getMessage()));
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, tenantLicensePolicy);
            return "tenantlicensepolicys/create";
        }
    }

    return "redirect:/tenantlicensepolicys/"
            + encodeUrlPathSegment(tenantLicensePolicy.getId().toString(), httpServletRequest);
}

From source file:org.jblogcms.core.account.controller.EditAccountController.java

/**
 * Returns saved account, if exceptions occurs translates them into {@link org.springframework.validation.FieldError}s
 * and adds those errors to the {@code BindingResult} object
 *
 * @param accountForm the new account//from   www  .  java  2s  . c o  m
 * @param result      the {@code BindingResult} object
 * @return the saved account
 */
private Account editAccount(Account accountForm, BindingResult result) {
    Account account = null;

    try {
        account = accountService.editAccount(accountForm);
    } catch (DuplicateEmailException e) {
        String errorCode = messageSource.getMessage(e.getLocalMessage(), null, null);

        FieldError error = new FieldError("user", "email", accountForm.getEmail(), false,
                new String[] { errorCode }, new Object[] {}, errorCode);
        result.addError(error);
    }
    return account;
}

From source file:org.jblogcms.core.blog.controller.AddBlogController.java

/**
 * Returns saved blog, if exceptions occurs translates them into {@link org.springframework.validation.FieldError}s
 * and adds those errors to the {@code BindingResult}
 *
 * @param blogForm         the new blog//from w w w. j a  v a 2 s . c om
 * @param currentAccountId the primary key of the account, blog creator
 * @param result           the {@code BindingResult} object
 * @return the saved blog
 */
private Blog addBlog(Blog blogForm, Long currentAccountId, BindingResult result) {

    Blog blog = null;
    try {
        blog = blogService.addBlog(blogForm, currentAccountId);

    } catch (DuplicateBlogNameException e) {

        String errorCode = messageSource.getMessage(e.getLocalMessage(), null, null);
        FieldError error = new FieldError("blog", "name", blogForm.getName(), false, new String[] { errorCode },
                new Object[] {}, errorCode);
        result.addError(error);

    } catch (DuplicateBlogUrlNameException e) {

        String errorCode = messageSource.getMessage(e.getLocalMessage(), null, null);
        FieldError error = new FieldError("blog", "urlName", blogForm.getUrlName(), false,
                new String[] { errorCode }, new Object[] {}, errorCode);
        result.addError(error);

    }
    return blog;
}

From source file:org.jdal.ui.bind.ControlBindingErrorProcessor.java

/** 
 * Add a ControlError instead FieldError to hold component that has failed.
 * @param control//from   w w  w  .  ja v  a  2s  . co  m
 * @param ex
 * @param bindingResult
 */
public void processPropertyAccessException(Object control, PropertyAccessException ex,
        BindingResult bindingResult) {
    // Create field error with the exceptions's code, e.g. "typeMismatch".
    String field = ex.getPropertyName();
    String[] codes = bindingResult.resolveMessageCodes(ex.getErrorCode(), field);
    Object[] arguments = getArgumentsForBindError(bindingResult.getObjectName(), field);
    Object rejectedValue = ex.getValue();
    if (rejectedValue != null && rejectedValue.getClass().isArray()) {
        rejectedValue = StringUtils.arrayToCommaDelimitedString(ObjectUtils.toObjectArray(rejectedValue));
    }
    bindingResult.addError(new ControlError(control, bindingResult.getObjectName(), field, rejectedValue, true,
            codes, arguments, ex.getLocalizedMessage()));
}

From source file:cs544.wamp_blog_engine.controller.UserController.java

@RequestMapping(value = "/addCredential", method = RequestMethod.POST)
public String addCredential(@Valid Credential credential, BindingResult result, HttpSession session) {
    String view = "redirect:/addUser";
    //dumb fix//from  w w  w.  j  a  v  a2s. com
    boolean used = userService.checkUserName(credential.getUsername());
    if (used) {
        FieldError f = new FieldError("credential", "username", credential.getUsername(), false, null, null,
                "Username : " + credential.getUsername() + " already in use");
        result.addError(f);
    }
    if (!result.hasErrors()) {
        User u = (User) session.getAttribute("loggedUser");
        if (u != null && u.getUserCredential().isAdmin()) {
            credential.setPreviledge("ROLE_ADMIN");
        } else {
            credential.setPreviledge("ROLE_BLOGGER");
        }
        credential.setBlocked(false);
        session.setAttribute("credential", credential);
    } else {
        view = "addCredential";
    }
    return view;
}

From source file:org.dspace.webmvc.controller.LoginController.java

/**
 * Method to authenticate the user credentials supplied in loginForm.
 * <p/>/*from w w  w .  j ava  2  s  . co m*/
 * Note that the order of parameters is important - the BindingResult must immediately follow the model attribute
 * being validated.
 *
 * @param context
 * @param loginService
 * @param loginForm
 * @param bindingResult
 * @return
 */
@RequestMapping(params = "submit")
public String processForm(@RequestAttribute Context context, LoginService loginService,
        @Valid LoginForm loginForm, BindingResult bindingResult) {
    if (!bindingResult.hasErrors()) {
        int status = AuthenticationManager.authenticate(context, loginForm.getEmail(), loginForm.getPassword(),
                null, null /*request*/);
        if (status == AuthenticationMethod.SUCCESS) {
            loginService.createUserSession(context, context.getCurrentUser());
            String redirectUrl = loginService.getInterruptedRequestURL();
            return "redirect:" + (StringUtils.isEmpty(redirectUrl) ? "/" : redirectUrl);
        } else {
            bindingResult.addError(new ObjectError("loginForm",
                    new String[] { "InvalidPassword.loginForm", "InvalidPassword" }, null /* arguments */,
                    "default message"));
        }
    }

    return "pages/login";
}

From source file:mx.edu.um.mateo.general.web.ProveedorController.java

@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpServletRequest request, @RequestParam Long id, Model modelo,
        @ModelAttribute Proveedor proveedor, BindingResult bindingResult,
        RedirectAttributes redirectAttributes) {
    log.debug("Elimina proveedor");
    try {//from   ww  w.j av a 2 s  .  co  m
        String nombre = proveedorDao.elimina(id);

        redirectAttributes.addFlashAttribute("message", "proveedor.eliminado.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { nombre });
    } catch (Exception e) {
        log.error("No se pudo eliminar la proveedor " + id, e);
        bindingResult.addError(
                new ObjectError("proveedor", new String[] { "proveedor.no.eliminado.message" }, null, null));
        return "admin/proveedor/ver";
    }

    return "redirect:/admin/proveedor";
}