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.appsolve.padelcampus.controller.LoginController.java

@RequestMapping(value = "register", method = POST)
public ModelAndView doRegister(@Valid @ModelAttribute("Model") Player player, BindingResult bindingResult,
        @RequestParam(value = "stay-logged-in", defaultValue = "false", required = false) Boolean stayLoggedIn,
        @RequestParam(value = "accept-tac", defaultValue = "false", required = false) Boolean acceptTAC,
        @RequestParam(value = "accept-pp", defaultValue = "false", required = false) Boolean acceptPP,
        HttpServletRequest request, HttpServletResponse response) {
    ModelAndView mav = getRegisterView(player, request, acceptTAC, acceptPP);
    if (bindingResult.hasErrors()) {
        return mav;
    }/*from w  ww .j a  v a  2  s. co  m*/
    try {
        if (!acceptTAC) {
            throw new Exception(msg.get("PleaseAcceptTAC"));
        }

        if (!acceptPP) {
            throw new Exception(msg.get("PleaseAcceptPP"));
        }

        if (StringUtils.isEmpty(player.getPassword())) {
            throw new Exception(msg.get("PasswordMayNotBeEmpty"));
        }

        if (player.getDeleted()) {
            throw new Exception(msg.get("CannotUseDeletedAccountEmail", new Object[] { player.getEmail() }));
        }

        Player persistedPlayer = playerDAO.findByEmail(player.getEmail());
        if (persistedPlayer != null && !StringUtils.isEmpty(persistedPlayer.getPasswordHash())) {
            throw new Exception(msg.get("EmailAlreadyRegistered"));
        }

        Player playerToPersist;
        if (persistedPlayer == null) {
            playerToPersist = player;
        } else {
            //update existing player instead of generating a new one
            playerToPersist = persistedPlayer;
            playerToPersist.setFirstName(player.getFirstName());
            playerToPersist.setLastName(player.getLastName());
            playerToPersist.setPhone(player.getPhone());
            playerToPersist.setGender(player.getGender());
            playerToPersist.setPassword(player.getPassword());
            playerToPersist.setAllowEmailContact(player.getAllowEmailContact());
        }

        //create player object which also generates a UUID
        playerToPersist = playerDAO.saveOrUpdate(playerToPersist);

        String accountVerificationLink = PlayerUtil.getAccountVerificationLink(request, playerToPersist);

        Mail mail = new Mail();
        mail.addRecipient(player);
        mail.setSubject(msg.get("RegistrationMailSubject"));
        String key = player.getAllowEmailContact() ? "RegistrationMailBody2" : "RegistrationMailBody";
        mail.setBody(StringEscapeUtils.unescapeJava(msg.get(key, new Object[] { playerToPersist.toString(),
                accountVerificationLink, RequestUtil.getBaseURL(request) })));
        try {
            mailUtils.send(mail, request);
        } catch (IOException | MailException e) {
            LOG.error(e.getMessage(), e);
        }

        //login user
        sessionUtil.setUser(request, playerToPersist);

        //set auto login cookie if user has requested so
        setLoginCookie(stayLoggedIn, request, response);

        String redirectPath = sessionUtil.getLoginRedirectPath(request);
        if (!StringUtils.isEmpty(redirectPath)) {
            sessionUtil.setLoginRedirectPath(request, null);
            return new ModelAndView("redirect:" + redirectPath);
        }
        return getRegisterSuccessView();
    } catch (Exception e) {
        LOG.warn("Error while registering user", e);
        bindingResult.addError(new ObjectError("id", e.getMessage()));
        return mav;
    }
}

From source file:de.appsolve.padelcampus.controller.LoginController.java

@RequestMapping(value = "forgot-password", method = POST)
public ModelAndView forgotPassowrd(@Valid @ModelAttribute("Model") Credentials credentials,
        BindingResult bindingResult, HttpServletRequest request) {
    ModelAndView forgotPasswordView = getForgotPasswordView(credentials);
    if (bindingResult.hasErrors()) {
        return forgotPasswordView;
    }/*from   w  w  w  .  j  a  va  2  s .c o  m*/
    try {
        if (StringUtils.isEmpty(credentials.getEmail())) {
            throw new Exception(msg.get("EmailMayNotBeEmpty"));
        }

        Player player = playerDAO.findByEmail(credentials.getEmail());
        if (player == null) {
            throw new Exception(msg.get("EmailAddressNotRegistered"));
        }
        if (player.getDeleted()) {
            throw new Exception(
                    msg.get("CannotUseDeletedAccountEmail", new Object[] { credentials.getEmail() }));
        }

        UUID randomUUID = UUID.randomUUID();
        String resetPasswordURL = RequestUtil.getBaseURL(request) + "/login/reset-password/"
                + randomUUID.toString();

        player.setPasswordResetUUID(randomUUID.toString());
        DateTime expiryDate = new DateTime(Constants.DEFAULT_TIMEZONE).plusDays(1);
        player.setPasswordResetExpiryDate(expiryDate);
        playerDAO.saveOrUpdate(player);

        Mail mail = new Mail();
        Contact contact = new Contact();
        contact.setEmailAddress(player.getEmail());
        contact.setEmailDisplayName(player.toString());
        mail.addRecipient(contact);
        mail.setSubject(msg.get("ForgotPasswordMailSubject"));
        mail.setBody(StringEscapeUtils.unescapeJava(msg.get("ForgotPasswordMailBody",
                new Object[] { player.toString(), resetPasswordURL, RequestUtil.getBaseURL(request) })));
        mailUtils.send(mail, request);
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
        bindingResult.addError(new ObjectError("email", e.getMessage()));
        return forgotPasswordView;
    }
    return new ModelAndView("login/forgot-password-success", "Email", credentials.getEmail());
}

From source file:de.appsolve.padelcampus.controller.LoginController.java

@RequestMapping(value = "reset-password/{UUID}", method = POST)
public ModelAndView resetPassword(@Valid @ModelAttribute("Model") Credentials credentials,
        BindingResult bindingResult, @PathVariable("UUID") String UUID) {
    ModelAndView mav = getResetPasswordView(credentials);
    Player player = playerDAO.findByPasswordResetUUID(UUID);

    if (!player.getEmail().equals(credentials.getEmail())) {
        bindingResult.addError(new ObjectError("email", "nice try"));
        return mav;
    }// ww  w. j a  va  2s  . c o  m

    if (player.getPasswordResetExpiryDate().isBeforeNow()) {
        bindingResult.addError(new ObjectError("email", msg.get("PasswordResetLinkExpired")));
        return mav;
    }

    if (StringUtils.isEmpty(credentials.getPassword())) {
        bindingResult.addError(new ObjectError("email", msg.get("PasswordMayNotBeEmpty")));
        return mav;
    }
    player.setPassword(credentials.getPassword());
    playerDAO.saveOrUpdate(player);
    return new ModelAndView("login/reset-password-success");
}

From source file:de.appsolve.padelcampus.controller.pro.ProOperatorsController.java

@RequestMapping(method = POST, value = "newaccount")
public ModelAndView postNewAccount(HttpServletRequest request,
        @ModelAttribute("Model") CustomerRegistrationModel customerAccount, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return new ModelAndView("pro/newaccount", "Model", customerAccount);
    }/*from  ww  w  .ja va 2 s.  c  om*/
    try {
        if (StringUtils.isEmpty(customerAccount.getCustomer().getName())) {
            throw new Exception(msg.get("ProjectNameFormatRequirements"));
        }
        String projectName = customerAccount.getCustomer().getName().toLowerCase(Constants.DEFAULT_LOCALE)
                .replace(" ", "-");
        //verify dns name requirements
        if (!DNS_SUBDOMAIN_PATTERN.matcher(projectName).matches()) {
            throw new Exception(msg.get("ProjectNameFormatRequirements"));
        }

        //make sure customer does not exist yet
        Customer customer = customerDAO.findByName(projectName);
        if (customer != null) {
            throw new Exception(msg.get("ProjectAlreadyExists"));
        }

        String dnsHostname = environment.getProperty("DNS_HOSTNAME");
        String cloudflareUrl = environment.getProperty("CLOUDFLARE_URL");
        //create DNS subdomain in cloudflare
        String domainName = cloudFlareApiClient.addCnameRecord(projectName, cloudflareUrl, dnsHostname);

        //save customer to DB
        HashSet<String> domainNames = new HashSet<>();
        domainNames.add(domainName);
        customerAccount.getCustomer().setDomainNames(domainNames);
        customer = customerDAO.saveOrUpdate(customerAccount.getCustomer());

        //create admin account in DB
        Player adminPlayer = playerDAO.findByEmail(customerAccount.getPlayer().getEmail());
        if (adminPlayer == null) {
            customerAccount.getPlayer().setCustomer(customer);
            adminPlayer = playerDAO.saveOrUpdate(customerAccount.getPlayer());
        }

        //create admin group in DB
        AdminGroup adminGroup = adminGroupDAO.findByAttribute("customer", customer);
        if (adminGroup == null) {
            adminGroup = new AdminGroup();
            adminGroup.setName(domainName + " Admins");
            EnumSet<Privilege> privileges = EnumSet.complementOf(EnumSet.of(Privilege.ManageCustomers));
            adminGroup.setPrivileges(privileges);
            adminGroup.setPlayers(new HashSet<>(Arrays.asList(new Player[] { adminPlayer })));
            adminGroup.setCustomer(customer);
            adminGroupDAO.saveOrUpdate(adminGroup);
        }

        //create all.min.css.stylesheet for new customer
        htmlResourceUtil.updateCss(servletContext, customer);

        Mail mail = new Mail();
        mail.addRecipient(getDefaultContact());
        mail.setSubject("New Customer Registration");
        mail.setBody(customer.toString());
        mailUtils.send(mail, request);

        return new ModelAndView("redirect:/pro/operators/newaccount/" + customer.getId());
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        errorReporter.notify(e);
        bindingResult.addError(new ObjectError("id", e.getMessage()));
        return new ModelAndView("pro/newaccount", "Model", customerAccount);
    }
}

From source file:de.hybris.platform.sap.productconfig.frontend.controllers.AbstractProductConfigController.java

private void restoreValidationErrorsInGroup(final Map<String, FieldError> userInputToRestore,
        final BindingResult bindingResult, final UiGroupData group) {
    for (final CsticData latestCstic : group.getCstics()) {
        final boolean restoreValidationError = latestCstic.isVisible()
                && latestCstic.getType() != UiType.READ_ONLY
                && userInputToRestore.containsKey(latestCstic.getKey());
        if (restoreValidationError) {
            latestCstic.setCsticStatus(CsticStatusType.ERROR);
            final FieldError fieldError = userInputToRestore.get(latestCstic.getKey());
            latestCstic.setValue(fieldError.getRejectedValue().toString());
            bindingResult.addError(fieldError);
            group.setGroupStatus(GroupStatusType.ERROR);
        }/*w w w. j  a  v a2 s .  c  om*/
    }

    final List<UiGroupData> subGroups = group.getSubGroups();
    if (null == subGroups) {
        return;
    }

    for (final UiGroupData subGroup : subGroups) {
        restoreValidationErrorsInGroup(userInputToRestore, bindingResult, subGroup);
    }
}

From source file:edu.uiowa.icts.bluebutton.controller.ClinicalDocumentController.java

@RequestMapping(value = "save.html", method = RequestMethod.POST)
public String save(@RequestParam("person.personId") Integer person_personId,
        @Valid @ModelAttribute("clinicalDocument") ClinicalDocument clinicalDocument, BindingResult result, // must immediately follow bound object
        @RequestParam("file") MultipartFile document, Model model) throws IOException {
    if (document.isEmpty()) {
        result.addError(new FieldError("clinicalDocument", "document", "may not be empty"));
    }/*  ww w .ja  v  a  2  s .  com*/
    if (result.hasErrors()) {
        model.addAttribute("personList", bluebuttonDaoService.getPersonService().list());
        return "/bluebutton/clinicaldocument/edit";
    } else {
        clinicalDocument.setPerson(bluebuttonDaoService.getPersonService().findById(person_personId));
        clinicalDocument.setDocument(document.getBytes());
        clinicalDocument.setName(document.getOriginalFilename());
        clinicalDocument.setDateUploaded(new Date());
        bluebuttonDaoService.getClinicalDocumentService().saveOrUpdate(clinicalDocument);
        return "redirect:/clinicaldocument/confirm?clinicalDocumentId="
                + clinicalDocument.getClinicalDocumentId();
    }
}

From source file:edu.uiowa.icts.bluebutton.controller.ClinicalDocumentController.java

@RequestMapping(value = "confirm", method = RequestMethod.POST)
public String confirmSave(@ModelAttribute("clinicalDocument") ClinicalDocument clinicalDocument, Model model,
        BindingResult result) {
    ClinicalDocument cd = this.bluebuttonDaoService.getClinicalDocumentService()
            .findById(clinicalDocument.getClinicalDocumentId());
    if (clinicalDocument.getSource() == null || clinicalDocument.getSource().trim().length() < 1) {
        result.addError(new FieldError("clinicalDocument", "source", "May not be empty"));
    }/*w ww  .j  a va2  s . c  o m*/
    if (result.hasErrors()) {
        clinicalDocument.setDocument(cd.getDocument());
        model.addAttribute("clinicalDocument", clinicalDocument);
        return "/bluebutton/clinicaldocument/confirmSource";
    } else {
        cd.setParsedJson(clinicalDocument.getParsedJson());
        cd.setSource(clinicalDocument.getSource().trim());
        cd.setJsonParserVersion("1.0.0");
        bluebuttonDaoService.getClinicalDocumentService().update(cd);
        return "redirect:/person/show?personId=".concat(cd.getPerson().getPersonId().toString());
    }
}

From source file:gr.abiss.calipso.userDetails.controller.ProviderSignInController.java

private void addFieldError(String objectName, String fieldName, String fieldValue, String errorCode,
        BindingResult result) {
    LOGGER.debug("Adding field error object's: {} field: {}", objectName, fieldName);
    FieldError error = new FieldError(objectName, fieldName, fieldValue, false, new String[] { errorCode },
            new Object[] {}, errorCode);

    result.addError(error);
    LOGGER.debug("Added field error: {} to binding result: {}", error, result);
}

From source file:mx.edu.um.mateo.colportor.web.AsociacionController.java

@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpServletRequest request, @RequestParam Long id, Model modelo,
        @ModelAttribute Asociacion Asociacion, BindingResult bindingResult,
        RedirectAttributes redirectAttributes) {
    log.debug("Elimina Asociacion");
    try {/*from www . j a va  2s . c  om*/
        Long unionId = ((Union) request.getSession().getAttribute(Constantes.SESSION_UNION)).getId();
        String nombre = asociacionDao.elimina(id, unionId);
        ambiente.actualizaSesion(request.getSession());
        redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE, "asociacion.eliminada.message");
        redirectAttributes.addFlashAttribute(Constantes.CONTAINSKEY_MESSAGE_ATTRS, new String[] { nombre });
    } catch (Exception e) {
        log.error("No se pudo eliminar la Asociacion " + id, e);
        bindingResult.addError(new ObjectError(Constantes.ADDATTRIBUTE_ASOCIACION,
                new String[] { "asociacion.no.eliminada.message" }, null, null));
        return Constantes.PATH_ASOCIACION_VER;
    }
    return "redirect:" + Constantes.PATH_ASOCIACION;
}

From source file:mx.edu.um.mateo.colportor.web.ClienteColportorController.java

@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpServletRequest request, @RequestParam Long id, Model modelo,
        @ModelAttribute ClienteColportor clienteColportor, BindingResult bindingResult,
        RedirectAttributes redirectAttributes) {
    log.debug("Elimina clienteColportor");
    try {// ww  w  .jav a  2s. c  om
        String nombre = clienteColportorDao.elimina(id);

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

    return "redirect:" + Constantes.CLIENTE_COLPORTOR_PATH;
}