Example usage for org.springframework.validation FieldError FieldError

List of usage examples for org.springframework.validation FieldError FieldError

Introduction

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

Prototype

public FieldError(String objectName, String field, String defaultMessage) 

Source Link

Document

Create a new FieldError instance.

Usage

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

private boolean changePassword(ChangePasswordDTO changePasswordDTO, BindingResult result) {

    if (!Objects.equals(changePasswordDTO.getPassword(), changePasswordDTO.getPasswordVerification())) {

        String errorCode = messageSource.getMessage("fieldError.passwordsNotEqual", null, null);
        FieldError error = new FieldError("changePasswordDTO", "passwordVerification", errorCode);
        result.addError(error);// w ww. jav  a  2  s  . c  o m
        return false;
    }

    try {
        accountService.changePassword(changePasswordDTO);
    } catch (OldPasswordNotMatchedException e) {
        String errorCode = messageSource.getMessage("exception.oldPasswordNotMatched", null, null);
        FieldError error = new FieldError("changePasswordDTO", "oldPassword", errorCode);
        result.addError(error);
        return false;
    }
    return true;
}

From source file:com.test.springmvc.springmvcproject.IndexController.java

@RequestMapping(value = "register", method = RequestMethod.POST)
public String register(HttpSession session, ModelMap model, @Valid RegisterBean bean, BindingResult result) {

    if (!result.hasErrors()) {
        System.out.println("Pas d'erreurs !!");
        session.setAttribute("email_utilisateur", bean.getEmail());
        try {/*  w w  w.  j  av a  2s  . co m*/
            utilisateurService.create(bean);
        } catch (DuplicatedEntryException e) {
            result.addError(new FieldError("RegisterBean", "email", e.getMessage()));
            return "register";
        }
    } else {
        System.out.println("erreur presentes dans la validation : " + result.toString());
        return "register";
    }

    return "redirect:/index.do";
}

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

private Account createAccount(NewAccountDTO newAccountDTO, BindingResult result) {

    Account account = null;/*w w  w . j  a  v  a 2  s.  c  o  m*/

    if (!Objects.equals(newAccountDTO.getPassword(), newAccountDTO.getPasswordVerification())) {

        String errorCode = messageSource.getMessage("fieldError.passwordsNotEqual", null, null);
        FieldError error = new FieldError("user", "passwordVerification", errorCode);
        result.addError(error);
        return null;
    }

    if (Objects.equals(newAccountDTO.getRole(), "admin")
            && accountService.countAllAccountsWithRoleAdmin() > 0) {

        String errorCode = messageSource.getMessage("fieldError.adminAccountExistsAlready", null, null);
        FieldError error = new FieldError("user", "*", errorCode);
        result.addError(error);
        return null;
    }

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

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

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

private boolean isUserNameValid(String userName, BindingResult errors) {
    if (userName == null || userName.trim().length() == 0) {
        errors.addError(new FieldError("signUpForm", "userName", "Please choose a username"));
        return false;
    } else {//from   ww w.  ja  v  a 2 s. co  m
        return true;
    }
}

From source file:com.test.springmvc.springmvcproject.UploadController.java

@RequestMapping(value = "", method = RequestMethod.POST)
public String addNewBook(final javax.servlet.http.HttpServletRequest request, @Valid BookBean bean,
        BindingResult result, ModelMap map, final HttpSession session) {
    //si erreur, on renvoie direct sur la page
    if (result.hasErrors()) {
        return "upload/newBook";
    }/*from   www .  j  a  v  a  2  s .co  m*/
    final String contextRoot = request.getServletContext().getRealPath("");
    final String contextPath = request.getContextPath();
    final String dossier_uploads = "uploads";
    final String dossier_default = "images";
    final String image_default = "default.png";

    final String uri_couverture_default = contextPath + "/" + dossier_default + "/" + image_default;
    //creation url totale pour la sauvegarde physique
    final String url_to_book = contextRoot + "/" + dossier_uploads + "/" + bean.getAuteur();
    //creation url relative pour sauvegarder l'emplacement des donnees
    final String uri_to_book = contextPath + "/" + dossier_uploads + "/" + bean.getAuteur();

    final String url_finale_livre = url_to_book + "/" + bean.getFichier().getOriginalFilename();
    final String url_relative_livre = uri_to_book + "/" + bean.getFichier().getOriginalFilename();
    //on ajoute l'emplacement final au bean book
    bean.setEmplacement(url_relative_livre);
    //on ajoute le nom du fichier au bean
    bean.setNomLivre(bean.getFichier().getOriginalFilename());

    if (!bean.getCouverture().isEmpty()) {
        final String url_relative_couverture = uri_to_book + "/" + bean.getCouverture().getOriginalFilename();
        bean.setEmplacementCouverture(url_relative_couverture);
    } else {
        bean.setEmplacementCouverture(uri_couverture_default);
    }
    final String url_finale_couverture = url_to_book + "/" + bean.getCouverture().getOriginalFilename();

    final File livre = new File(url_finale_livre);
    final File couverture = new File(url_finale_couverture);
    try {
        livre.getParentFile().mkdirs();
        bean.getFichier().transferTo(livre);
        if (!bean.getCouverture().isEmpty()) {
            bean.getCouverture().transferTo(couverture);
        }

        //recuperation de l'utilisateur
        UtilisateurBean utilisateur = (UtilisateurBean) session.getAttribute("utilisateur");
        //si pas d'utilisateur, on recupere l'anonyme
        if (null == utilisateur) {
            try {
                utilisateur = utilisateurService.get("anonyme@anonyme.com");
            } catch (NoDataFoundException e) {
                result.addError(new FieldError("BookBean", "fichier", "Une erreur interne est apparue."));
            }
        }
        //creation entree en base
        try {
            service.createEntry(bean, utilisateur);
        } catch (BookAlreadyExistsException e) {
            result.addError(new FieldError("BookBean", "fichier", "Livre deja existant"));
            return "upload/newBook";
        }
    } catch (IOException e) {
        result.addError(new FieldError("BookBean", "fichier",
                "Une erreur est survenue lors du transfert." + e.getMessage()));
        return "upload/newBook";
    }

    return "redirect:/index.do";
}

From source file:ch.javaee.basicMvc.web.controller.UserController.java

@RequestMapping(value = "/public/signup_confirm", method = RequestMethod.POST)
@Transactional//w w  w. j  a v  a2s. c o m
public String createUser(Model model, @ModelAttribute("user") @Valid UserForm form, BindingResult result,
        @RequestParam(value = "recaptcha_challenge_field", required = false) String challangeField,
        @RequestParam(value = "recaptcha_response_field", required = false) String responseField,
        ServletRequest servletRequest) {
    logger.debug("Enter: createUser");
    if (reCaptcha != null) {
        String remoteAdress = servletRequest.getRemoteAddr();
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAdress, challangeField,
                responseField);
        if (!reCaptchaResponse.isValid()) {
            this.create(model);
            return "view/public/signup";
        }
    }
    if (!result.hasErrors()) {

        // check if email already exists
        if (userRepository.isEmailAlreadyExists(form.getEmail())) {
            FieldError fieldError = new FieldError("user", "email", "email already exists");
            result.addError(fieldError);
            return "view/public/signup";
        }
        User user = new User();
        Md5PasswordEncoder encoder = new Md5PasswordEncoder();
        user.setUsername(form.getUsername());
        user.setEmail(form.getEmail());
        user.setEnabled(false);

        user.setPassword(encoder.encodePassword(form.getPassword(), user.getEmail()));
        Role role = new Role();
        role.setUser(user);
        role.setRole(2);

        SecurityCode securityCode = new SecurityCode();
        securityCode.setUser(user);
        securityCode.setTimeRequest(new Date());
        securityCode.setTypeActivationEnum(TypeActivationEnum.NEW_ACCOUNT);
        securityCode.setCode(SecureUtility.generateRandomCode());
        user.setRole(role);
        user.setSecurityCode(securityCode);

        userRepository.saveUser(user);
        //securityCodeRepository.persist(securityCode);
        mailSenderService.sendAuthorizationMail(user, user.getSecurityCode());

    } else {
        logger.debug("signup error");
        this.create(model);
        return "view/public/signup";

    }
    logger.debug("Exit: createUser");
    return "view/public/mailSent";
}

From source file:com.web.mavenproject6.controller.UserController.java

@RequestMapping(value = "/public/signup_confirm", method = RequestMethod.POST)
@Transactional//  www .  ja  v  a2s  .  co  m
public String createUser(Model model, @ModelAttribute("user") @Valid UserForm form, BindingResult result,
        @RequestParam(value = "recaptcha_challenge_field", required = false) String challangeField,
        @RequestParam(value = "recaptcha_response_field", required = false) String responseField,
        ServletRequest servletRequest) throws GeneralSecurityException {

    if (reCaptcha != null) {
        String remoteAdress = servletRequest.getRemoteAddr();
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAdress, challangeField,
                responseField);
        if (!reCaptchaResponse.isValid()) {
            this.create(model);
            return "thy/public/signup";
        }
    }
    if (!result.hasErrors()) {
        if (userService.isUserExistByEmail(form.getEmail())) {
            FieldError fieldError = new FieldError("user", "email", "email already exists");
            result.addError(fieldError);
            return "thy/public/signup";
        }

        if (userService.isUserExistByLogin(form.getEmail())) {
            FieldError fieldError = new FieldError("user", "username", "login already exists");
            result.addError(fieldError);
            return "thy/public/signup";
        }

        Users user = new Users();

        user.setLogin(form.getUsername());
        user.setEmail(form.getEmail());
        user.setEnabled(false);
        user.setPassword(form.getPassword());

        Role role = new Role();
        role.setUser(user);
        role.setRole(2);

        SecurityCode securityCode = new SecurityCode();
        securityCode.setUser(user);
        securityCode.setTimeRequest(new Date());
        securityCode.setTypeActivationEnum(TypeActivationEnum.NEW_ACCOUNT);
        securityCode.setCode(SecureUtility.generateRandomCode());
        user.setRole(role);
        user.setSecurityCode(securityCode);

        personal person = new personal();
        person.setUser(user);
        person.setPhoto(new byte[1]);
        user.setPerson(person);
        userService.save(user);

        /* for generate accessNumber by userId */
        user = userService.getRepository().findUserByEmail(user.getEmail());
        person = user.getPerson();
        person.setAccessNumber(formatNum("" + user.getId()));
        user.setPerson(person);
        userService.save(user);

        securityCodeRepository.save(securityCode);
        mailSenderService.sendAuthorizationMail(user, user.getSecurityCode());

    } else {
        this.create(model);
        return "thy/public/signup";

    }
    return "thy/public/mailSent";
}

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  va  2 s  . c  o m
    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:com.devnexus.ting.web.controller.RegisterController.java

@RequestMapping(value = "/s/register", method = RequestMethod.POST)
public String validateInitialFormAndPrepareDetailsForm(Model model, @Valid RegisterForm registerForm,
        BindingResult result) {/*from w ww  .ja  v  a 2  s . c om*/

    Event currentEvent = businessService.getCurrentEvent();
    EventSignup eventSignup = businessService.getEventSignup();
    prepareHeader(currentEvent, model);
    model.addAttribute("signupRegisterView", new SignupRegisterView(eventSignup));

    int totalTickets = 0;

    for (int i = 0; i < registerForm.getTicketGroupRegistrations().size(); i++) {
        RegisterForm.TicketGroupRegistration ticketReg = registerForm.getTicketGroupRegistrations().get(i);
        TicketGroup ticketGroup = businessService.getTicketGroup(ticketReg.getTicketGroupId());
        ticketReg.setGroup(ticketGroup);
        if (ticketReg.getTicketCount() > 0 && ticketReg.getTicketCount() < ticketGroup.getMinPurchase()) {
            result.addError(new FieldError("registerForm", "ticketGroupRegistrations[" + i + "].ticketCount",
                    "You need to buy more tickets."));
        }

        totalTickets += ticketReg.getTicketCount();

        if (ticketGroup.getCouponCodes() != null && ticketGroup.getCouponCodes().size() > 0
                && !Strings.isNullOrEmpty(ticketReg.getCouponCode())) {
            if (!hasCode(ticketGroup.getCouponCodes(), ticketReg.getCouponCode())) {
                result.addError(new FieldError("registerForm", "ticketGroupRegistrations[" + i + "].couponCode",
                        "Invalid Coupon Code."));
            }
        }
    }

    if (totalTickets == 0) {
        for (int i = 0; i < registerForm.getTicketGroupRegistrations().size(); i++) {
            result.addError(new FieldError("registerForm", "ticketGroupRegistrations[" + i + "].ticketCount",
                    "You must purchase a ticket to continue."));
        }
    }

    if (result.hasErrors()) {
        model.addAttribute("registerForm", registerForm);
        return "register";
    }

    RegistrationDetails registerFormPageTwo = new RegistrationDetails();
    registerFormPageTwo.copyPageOne(registerForm);

    registerFormPageTwo.setFinalCost(getTotal(registerFormPageTwo));

    model.addAttribute("registrationDetails", registerFormPageTwo);

    return "register2";

}