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.admin.controller.events.AdminEventsController.java

@RequestMapping(method = POST, value = "event/{eventId}/groupgamesend/{round}")
public ModelAndView saveEventGroupGamesEndForRound(@PathVariable() Long eventId, @PathVariable Integer round,
        @ModelAttribute("Model") Event dummy, BindingResult result) {
    Event event = eventDAO.findByIdFetchWithParticipantsAndGames(eventId);
    try {//w w w . ja  v  a 2 s.  c  o  m
        SortedMap<Integer, List<Game>> roundGames = eventsUtil.getRoundGameMap(event, round + 1);
        if (!roundGames.isEmpty()) {
            throw new Exception(msg.get("GroupGamesAlreadyEnded"));
        }

        SortedMap<Integer, List<Game>> groupGames = eventsUtil.getGroupGameMap(event, round);
        if (groupGames.isEmpty()) {
            throw new Exception(msg.get("NoGroupGames"));
        }
        getRankedGroupParticipants(groupGames, event.getNumberOfGroups(), event.getNumberOfWinnersPerGroup());

        return redirectToGroupDrawsRound(event, round + 1);
    } catch (Exception e) {
        result.addError(new ObjectError("*", e.getMessage()));
        return getGroupGamesEndView(dummy, round);
    }
}

From source file:de.appsolve.padelcampus.admin.controller.events.AdminEventsController.java

@RequestMapping(method = POST, value = "/{eventId}/addguests")
public ModelAndView postAddGuests(@PathVariable("eventId") Long eventId,
        @ModelAttribute("Player") Player player, @RequestParam("NumberOfGuests") Long numberOfGuests,
        HttpServletRequest request, BindingResult result) {
    Event event = eventDAO.findByIdFetchWithParticipants(eventId);
    try {/*from   www  . j a v a  2 s.c  o  m*/
        Player primaryPlayer;
        if (StringUtils.isEmpty(player.getUUID())) {
            validator.validate(player, result);
            if (result.hasErrors()) {
                return getAddGuestsView(event, player, numberOfGuests);
            }
            if (playerDAO.findByEmail(player.getEmail()) != null) {
                throw new Exception(msg.get("EmailAlreadyRegistered"));
            }
            player.setAllowEmailContact(false);
            primaryPlayer = playerDAO.saveOrUpdate(player);
        } else {
            primaryPlayer = playerDAO.findByUUID(player.getUUID());
        }
        if (event.getParticipants().contains(primaryPlayer)) {
            throw new Exception(msg.get("AlreadyParticipatesInThisEvent", new Object[] { primaryPlayer }));
        }
        for (long guestNumber = 1L; guestNumber <= numberOfGuests; guestNumber++) {
            String domain = request.getServerName().equals("localhost") ? "localhost.local"
                    : request.getServerName();
            String guestEmail = String.format("%s-%s-Gast-%s@%s", primaryPlayer.getFirstName(),
                    primaryPlayer.getLastName(), guestNumber, domain).replace(" ", "-");
            Player guest = playerDAO.findByEmail(guestEmail);
            if (guest == null) {
                guest = new Player();
                guest.setFirstName(primaryPlayer.getFirstName());
                guest.setLastName(String.format("%s Gast %s", primaryPlayer.getLastName(), guestNumber));
                guest.setAllowEmailContact(false);
                guest.setEmail(guestEmail);
                guest.setPhone(primaryPlayer.getPhone());
                guest.setGender(primaryPlayer.getGender());
                guest = playerDAO.saveOrUpdate(guest);
            }
            event.getParticipants().add(guest);
        }
        event.getParticipants().add(primaryPlayer);
        eventDAO.saveOrUpdate(event);
        return new ModelAndView("redirect:/admin/events/edit/" + eventId);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        result.addError(new ObjectError("id", e.getMessage()));
        return getAddGuestsView(event, player, numberOfGuests);
    }
}

From source file:de.appsolve.padelcampus.admin.controller.general.AdminGeneralModulesController.java

@Override
public ModelAndView postEditView(@ModelAttribute("Model") Module model, HttpServletRequest request,
        BindingResult result) {
    if (result.hasErrors()) {
        return getEditView(model);
    }/*from   w w  w  .ja va  2  s . c om*/
    if (model.getModuleType().equals(ModuleType.HomePage)) {
        model.setShowOnHomepage(Boolean.FALSE);
        model.setShowInMenu(Boolean.FALSE);
        model.setShowInFooter(Boolean.FALSE);
    }
    if (model.getModuleType().equals(ModuleType.Events) && model.getEventGroups() != null) {
        List<Module> eventModules = moduleDAO.findByModuleType(ModuleType.Events);
        eventModules.remove(model);
        for (Module existingModule : eventModules) {
            if (existingModule.getEventGroups() != null) {
                if (!Collections.disjoint(existingModule.getEventGroups(), model.getEventGroups())) {
                    result.addError(new ObjectError("*", msg.get("EventGroupIsAlreadyAssociatedWith",
                            new Object[] { existingModule.getTitle() })));
                    break;
                }
            }
        }
    }
    checkTitleRequirements(model, result);
    if (result.hasErrors()) {
        return getEditView(model);
    }
    keepSubModules(model);
    checkPosition(model);
    rewriteLinks(model);

    ModelAndView mav = super.postEditView(model, request, result);
    moduleUtil.reloadModules(request);
    return mav;
}

From source file:de.appsolve.padelcampus.admin.controller.mail.AdminMailController.java

@RequestMapping(method = POST)
public ModelAndView postMail(HttpServletRequest request, @ModelAttribute("Model") Mail mail,
        BindingResult result) {
    if (mail.getTemplateId() != null
            && (mail.getTemplateId().equals("TextEmail") || mail.getTemplateId().equals("HTMLEmail"))) {
        validator.validate(mail, result);
    }//ww w.j  a v a2 s  .  com
    if (result.hasErrors()) {
        return getMailView(mail);
    }
    try {
        if (mail.getTemplateId() != null && !mail.getTemplateId().equals("TextEmail")
                && !mail.getTemplateId().equals("HTMLEmail")) {
            for (EmailContact contact : mail.getRecipients()) {
                Map<String, Object> substitutionData = new HashMap<>();

                //create uuid per contact
                String uuid = UUID.randomUUID().toString();

                //save in db
                EmailConfirmation emailConfirmation = new EmailConfirmation();
                emailConfirmation.setUuid(uuid);
                emailConfirmation.setEmail(contact.getEmailAddress());
                emailConfirmationDAO.saveOrUpdate(emailConfirmation);

                //add to map
                substitutionData.put("CONFIRM_EMAIL_LINK",
                        RequestUtil.getBaseURL(request) + "/email/confirm/" + uuid);
                substitutionData.put("UNSUBSCRIBE_EMAIL_LINK",
                        RequestUtil.getBaseURL(request) + "/email/unsubscribe/" + uuid);
                substitutionData.put("USERNAME", contact.getEmailDisplayName());
                substitutionData.put("SALUTATION",
                        contact.getGender().equals(Gender.male) ? "Lieber" : "Liebe");
                contact.setSubstitutionData(substitutionData);
            }
        }

        MailResult mailResult = mailUtils.send(mail, request);
        return new ModelAndView("admin/mail-success", "MailResult", mailResult);
    } catch (IOException | MailException e) {
        result.addError(new ObjectError("*", e.getMessage()));
        return getMailView(mail);
    }
}

From source file:de.appsolve.padelcampus.controller.events.EventsBookingController.java

@RequestMapping(method = POST, value = "/{eventId}/participate")
@Transactional//  w  w  w  .  j  a va  2 s . c o m
public ModelAndView postParticipate(@PathVariable("eventId") Long eventId, HttpServletRequest request,
        final @ModelAttribute("EventBookingRequest") EventBookingRequest eventBookingRequest,
        BindingResult bindingResult) {
    ModelAndView participateView = participateView(eventId, eventBookingRequest);
    try {
        Player user = sessionUtil.getUser(request);
        if (user == null) {
            return getLoginRequiredView(request, msg.get("Participate"));
        }

        Event event = eventDAO.findByIdFetchWithParticipantsAndCommunities(eventId);

        Booking booking = new Booking();
        booking.setPlayer(user);
        booking.setBookingDate(event.getStartDate());
        booking.setBookingTime(event.getStartTime());
        booking.setAmount(event.getPrice());
        booking.setCurrency(event.getCurrency());
        booking.setPaymentMethod(eventBookingRequest.getPaymentMethod());
        booking.setBookingType(BookingType.loggedIn);
        booking.setEvent(event);

        switch (event.getEventType()) {
        case PullRoundRobin:
            break;
        case CommunityRoundRobin:
            // remove players without any information
            List<Player> newPlayers = StreamSupport
                    .stream(eventBookingRequest.getNewPlayers().spliterator(), false)
                    .filter(player -> !(StringUtils.isEmpty(player.getFirstName())
                            && StringUtils.isEmpty(player.getLastName())
                            && StringUtils.isEmpty(player.getEmail())
                            && StringUtils.isEmpty(player.getPhone())))
                    .collect(Collectors.toList());

            // if at least one field is given, validate all data
            newPlayers.forEach(player -> validator.validate(player, bindingResult));
            if (bindingResult.hasErrors()) {
                return participateView;
            }

            // make sure at least one person participates
            if (newPlayers.isEmpty() && (eventBookingRequest.getPlayers() == null
                    || eventBookingRequest.getPlayers().isEmpty())) {
                throw new Exception(msg.get("PleaseAddParticipants"));
            }

            // check if email already exists
            for (Player player : newPlayers) {
                if (playerDAO.findByEmail(player.getEmail()) != null) {
                    throw new Exception(msg.get("EmailAlreadyRegistered"));
                }
            }

            // make sure community name exists
            Community community = eventBookingRequest.getCommunity();
            if (StringUtils.isEmpty(community.getName())) {
                throw new Exception(msg.get("PleaseAddCommunityName"));
            }
            booking.setCommunity(community);

            Set<Player> allPlayers = new HashSet<>(eventBookingRequest.getPlayers());
            newPlayers.forEach(newPlayer -> allPlayers.add(playerDAO.saveOrUpdate(newPlayer)));

            //do not add user as this would cause duplicate key (player and players go into the same table), instead use transient boolean value
            allPlayers.remove(user);
            booking.setPlayers(allPlayers);
            booking.setPlayerParticipates(eventBookingRequest.getPlayers() != null
                    && eventBookingRequest.getPlayers().contains(user));
            break;
        default:
            Player player = eventBookingRequest.getPlayer();
            Player partner;
            if (player.getUUID() == null) {
                validator.validate(player, bindingResult);
                if (bindingResult.hasErrors()) {
                    return participateView;
                }
                if (playerDAO.findByEmail(player.getEmail()) != null) {
                    throw new Exception(msg.get("EmailAlreadyRegistered"));
                }
                partner = playerDAO.saveOrUpdate(player);
            } else {
                partner = playerDAO.findByUUID(player.getUUID());
                if (partner == null) {
                    throw new Exception(msg.get("ChoosePartner"));
                }
                if (partner.equals(user)) {
                    throw new Exception(msg.get("ChooseDifferentPartner"));
                }
            }

            Set<Player> participants = new HashSet<>();
            //do not add user as this would cause duplicate key (player and players go into the same table)
            participants.add(partner);

            //extra fields
            booking.setPlayers(participants);
        }
        isEventBookingPossible(booking);

        sessionUtil.setBooking(request, booking);
        return new ModelAndView("redirect:/events/bookings/" + event.getId() + "/confirm");
    } catch (Exception e) {
        bindingResult.addError(new ObjectError("*", e.getMessage()));
        return participateView;
    }
}

From source file:de.appsolve.padelcampus.controller.events.EventsController.java

@RequestMapping(value = { "edit/{eventId}/addpullgame" }, method = POST)
public ModelAndView postAddPullGame(HttpServletRequest request, @PathVariable("eventId") Long eventId,
        @ModelAttribute("Model") AddTeamGame addTeamGame,
        @RequestParam(value = "redirectUrl", required = false) String redirectUrl,
        BindingResult bindingResult) {
    Player user = sessionUtil.getUser(request);
    if (user == null) {
        return getLoginView(request, request.getRequestURI());
    }//from  w  w w. ja v  a2 s .c  o  m
    Event event = eventDAO.findByIdFetchWithParticipants(eventId);
    validator.validate(addTeamGame, bindingResult);
    if (bindingResult.hasErrors()) {
        return getAddPullGameView(event, addTeamGame);
    }
    if (!Collections.disjoint(addTeamGame.getTeams().get(0).getPlayers(),
            addTeamGame.getTeams().get(1).getPlayers())) {
        bindingResult.addError(new ObjectError("id", msg.get("ChooseDistinctPlayers")));
        return getAddPullGameView(event, addTeamGame);
    }
    List<Participant> teams = new ArrayList<>();
    teams.add(teamDAO.findOrCreateTeam(addTeamGame.getTeams().get(0).getPlayers()));
    teams.add(teamDAO.findOrCreateTeam(addTeamGame.getTeams().get(1).getPlayers()));
    List<Game> eventGames = gameDAO.findByEventWithPlayers(event);
    for (Game game : eventGames) {
        if (game.getParticipants().containsAll(teams)) {
            bindingResult.addError(new ObjectError("id", msg.get("GameAlreadyExists")));
            return getAddPullGameView(event, addTeamGame);
        }
    }
    saveGame(event, teams, request);

    if (!StringUtils.isEmpty(redirectUrl)) {
        return new ModelAndView("redirect:/" + redirectUrl);
    }
    return new ModelAndView("redirect:/events/event/" + event.getId() + "/pullgames");
}

From source file:de.appsolve.padelcampus.controller.events.EventsController.java

@RequestMapping(value = { "edit/{eventId}/addfriendlygame" }, method = POST)
public ModelAndView postAddFriendlyGame(@PathVariable("eventId") Long eventId,
        @ModelAttribute("Model") AddTeamGame addTeamGame,
        @RequestParam(value = "redirectUrl", required = false) String redirectUrl, BindingResult bindingResult,
        HttpServletRequest request) {/* ww  w  .  jav  a2  s  . c  o  m*/
    Player user = sessionUtil.getUser(request);
    if (user == null) {
        return getLoginView(request, request.getRequestURI());
    }
    Event event = eventDAO.findByIdFetchWithParticipants(eventId);
    validator.validate(addTeamGame, bindingResult);
    if (bindingResult.hasErrors()) {
        return getAddFriendlyGameView(event, addTeamGame);
    }
    if (!Collections.disjoint(addTeamGame.getTeams().get(0).getPlayers(),
            addTeamGame.getTeams().get(1).getPlayers())) {
        bindingResult.addError(new ObjectError("id", msg.get("ChooseDistinctPlayers")));
        return getAddFriendlyGameView(event, addTeamGame);
    }
    List<Participant> teams = new ArrayList<>();
    teams.add(teamDAO.findOrCreateTeam(addTeamGame.getTeams().get(0).getPlayers()));
    teams.add(teamDAO.findOrCreateTeam(addTeamGame.getTeams().get(1).getPlayers()));

    saveGame(event, teams, request);

    if (!StringUtils.isEmpty(redirectUrl)) {
        return new ModelAndView("redirect:/" + redirectUrl);
    }
    return new ModelAndView("redirect:/events/event/" + event.getId() + "/pullgames");
}

From source file:de.appsolve.padelcampus.controller.events.EventsController.java

@RequestMapping(value = { "edit/{eventId}/addcommunitygame" }, method = POST)
public ModelAndView postAddCommunityGame(HttpServletRequest request, @PathVariable("eventId") Long eventId,
        @ModelAttribute("Model") AddTeamGame addTeamGame,
        @RequestParam(value = "redirectUrl", required = false) String redirectUrl,
        BindingResult bindingResult) {
    Event event = eventDAO.findByIdFetchWithParticipants(eventId);
    if (event == null) {
        throw new ResourceNotFoundException();
    }/*from w w  w  .  jav  a2  s  .c  o m*/
    try {
        Player user = sessionUtil.getUser(request);
        if (user == null) {
            return getLoginView(request, request.getRequestURI());
        }
        validator.validate(addTeamGame, bindingResult);
        if (bindingResult.hasErrors()) {
            return getAddCommunityGameView(event, addTeamGame);
        }
        Team team0 = addTeamGame.getTeams().get(0);
        Team team1 = addTeamGame.getTeams().get(1);
        if (team0.getPlayers().size() != 2 || team1.getPlayers().size() != 2) {
            throw new Exception(msg.get("ChooseTwoPlayersPerTeam"));
        }
        if (!Collections.disjoint(team0.getPlayers(), team1.getPlayers())) {
            throw new Exception(msg.get("ChooseDistinctPlayers"));
        }
        if (team0.getCommunity().equals(team1.getCommunity())) {
            throw new Exception(msg.get("ChooseDistinctCommunities"));
        }
        List<Participant> teams = new ArrayList<>();
        teams.add(findOrUpdateTeam(team0));
        teams.add(findOrUpdateTeam(team1));
        List<Game> eventGames = gameDAO.findByEventWithPlayers(event);
        for (Game game : eventGames) {
            if (game.getParticipants().containsAll(teams)) {
                bindingResult.addError(new ObjectError("id", msg.get("GameAlreadyExists")));
                return getAddCommunityGameView(event, addTeamGame);
            }
        }
        saveGame(event, teams, request);

        if (!StringUtils.isEmpty(redirectUrl)) {
            return new ModelAndView("redirect:/" + redirectUrl);
        }
        return new ModelAndView("redirect:/events/event/" + event.getId() + "/communitygames");
    } catch (Exception e) {
        bindingResult.addError(new ObjectError("id", e.getMessage()));
        return getAddCommunityGameView(event, addTeamGame);
    }
}

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

@RequestMapping(method = POST)
public ModelAndView doLogin(@Valid @ModelAttribute("Model") Credentials credentials,
        @RequestParam(value = "stay-logged-in", defaultValue = "false", required = false) Boolean stayLoggedIn,
        BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) {
    ModelAndView loginView = getLoginView(credentials, request);
    try {/*w  w  w. j  a va 2s  .  co m*/
        doLogin(credentials, stayLoggedIn, request, response);
    } catch (Exception e) {
        bindingResult.addError(new ObjectError("email", e.getMessage()));
        return loginView;
    }

    String redirectPath = sessionUtil.getLoginRedirectPath(request) == null ? "/" + PATH_HOME
            : sessionUtil.getLoginRedirectPath(request);
    sessionUtil.setLoginRedirectPath(request, null);
    return new ModelAndView("redirect:" + redirectPath);
}

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

@RequestMapping(value = "pre-register", method = POST)
public ModelAndView doPreRegister(@Valid @ModelAttribute("Model") Credentials credentials,
        BindingResult bindingResult, HttpServletRequest request) {
    ModelAndView loginView = getLoginView(credentials, request);
    if (bindingResult.hasErrors()) {
        return loginView;
    }//from  w ww  . j a va 2 s. co  m
    try {
        Player player = playerDAO.findByEmail(credentials.getEmail());
        if (player == null) {
            player = new Player();
        } else if (player.getDeleted()) {
            throw new Exception(msg.get("CannotUseDeletedAccountEmail", new Object[] { player.getEmail() }));
        } else if (!player.getGuest()) {
            throw new Exception(msg.get("EmailAlreadyRegistered"));
        }
        player.setEmail(credentials.getEmail());
        player.setPassword(credentials.getPassword());
        return getRegisterView(player, request, Boolean.FALSE, Boolean.FALSE);
    } catch (Exception e) {
        bindingResult.addError(new ObjectError("email", e.getMessage()));
        return loginView;
    }
}