List of usage examples for org.springframework.validation BindingResult addError
void addError(ObjectError error);
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractUsersController.java
/** * @param form//from w w w. j a va 2 s . c o m * @param result * @param map * @param status * @return */ @RequestMapping(value = { "/{userParam}/myprofile" }, method = RequestMethod.POST) public String edit(@PathVariable String userParam, @Valid @ModelAttribute("user") UserForm form, BindingResult result, HttpServletRequest request, ModelMap map, SessionStatus status) { logger.debug("###Entering in edit(form,result,map,status) method @POST"); com.citrix.cpbm.access.User user = form.getUser(); MyProfileValidator validator = new MyProfileValidator(); validator.validate(form, result); if (result.hasErrors() && !(result.getErrorCount() == 1 && result.getAllErrors().get(0).getCode().equals("Size") && form.getUser().getUsername().equals("root"))) { displayErrors(result); // TODO to return the edit page with errors return "redirect:/portal/users/" + userParam + "/myprofile"; } User logedInUser = this.getCurrentUser(); if (isEmailBlacklisted(user.getEmail().toLowerCase())) { logger.info("Email Id : " + form.getUser().getEmail() + " rejected because it is not on the whitelist or part of the blacklist. Kindly contact support"); result.rejectValue("user.email", "signup.emaildomain.blacklist.error"); return edit(null, user.getObject().getUuid(), request, map); } if (form.getClearPassword() != null && !form.getClearPassword().isEmpty()) { // password reset if (form.getOldPassword() == null) { result.addError(new FieldError(result.getObjectName(), "oldPassword", null, false, new String[] { "errors.password.required" }, null, null)); } else if (!user.getObject().authenticate(form.getOldPassword())) { result.addError(new FieldError(result.getObjectName(), "oldPassword", null, false, new String[] { "errors.password.invalid" }, null, null)); } else { user.getObject().setClearPassword(form.getClearPassword()); } } com.citrix.cpbm.access.User userClone = form.getUserClone(); // TODO need to do Validation(Once fix this then remove @Ignore annotation against testUpdateUserFail from Test // Suit. form.setPhone(form.getPhone().replaceAll(PHONE_NUMBER_REGEX, "")); // removing all characters from phone number String oldPhone = userClone.getPhoneWithoutIsdCode() != null ? userClone.getPhoneWithoutIsdCode() : ""; boolean phoneVerificationEnabled = false; if (!form.getPhone().equals(oldPhone.replaceAll(PHONE_NUMBER_REGEX, "")) || !form.getCountryCode().toString().equals(user.getCountryCode())) { if (connectorManagementService.getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION) != null && ((TelephoneVerificationService) connectorManagementService .getOssServiceInstancebycategory(ConnectorType.PHONE_VERIFICATION)).isEnabled()) { phoneVerificationEnabled = true; } if (phoneVerificationEnabled && !userService.hasAuthority(logedInUser, "ROLE_ACCOUNT_CRUD")) { String generatedPhoneVerificationPin = (String) request.getSession() .getAttribute("phoneVerificationPin"); String actualPhoneNumber = (String) request.getSession().getAttribute("phoneNumber"); if (form.getUserEnteredPhoneVerificationPin() == null || !form.getUserEnteredPhoneVerificationPin().equals(generatedPhoneVerificationPin) || !areDigitsInPhoneNosEqual(form.getPhone(), actualPhoneNumber)) { map.addAttribute("userEditError", "phoneVerfication.error"); result.rejectValue("phone", "phoneVerfication.error"); parseResult(result, map); return edit(null, user.getObject().getUuid(), request, map); } } } String phoneNo = form.getCountryCode().replaceAll(PHONE_NUMBER_REGEX, "") + COUNTRY_CODE_TO_PHONE_NUMBER_SEPERATOR + form.getPhone().replaceAll(PHONE_NUMBER_REGEX, ""); // Set the phone number if (!phoneVerificationEnabled && StringUtils.isEmpty(form.getPhone())) { user.setPhone(null); } else { user.setPhone(phoneNo); } if ((user.getObject().getTenant().getState() == State.ACTIVE || user.getObject().getTenant().getState() == State.LOCKED || user.getObject().getTenant().getState() == State.SUSPENDED) && !user.getEmail().equals(userClone.getEmail())) { userAlertPreferencesService.createUserAlertPreference(user.getObject(), user.getEmail(), AlertType.USER_EMAIL); // set email so that it wont be updated in users table and other places user.setEmail(userClone.getEmail()); user.setEmailVerified(true); } userService.update(user, result); form.setUser(user); map.addAttribute("user", form); setPage(map, Page.USER_PERSONAL_PROFILE); status.setComplete(); logger.debug("###Exiting edit(form,result,map,status) method @POST"); map.clear(); return "redirect:/portal/users/" + user.getObject().getParam() + "/myprofile"; }
From source file:com.octanner.controllers.AbstractProductConfigController.java
private void restoreValidationErrorsInGroup(final Map<String, FieldError> userInputToRestore, final BindingResult bindingResult, final UiGroupData group) { for (final CsticData latestCstic : group.getCstics()) { final UiType uiType = latestCstic.getType(); final boolean restoreValidationError = latestCstic.isVisible() && uiType != UiType.READ_ONLY && userInputToRestore.containsKey(latestCstic.getKey()); if (restoreValidationError) { latestCstic.getConflicts().clear(); latestCstic.setCsticStatus(CsticStatusType.ERROR); final FieldError fieldError = userInputToRestore.get(latestCstic.getKey()); final String errorValue = fieldError.getRejectedValue().toString(); if (UiType.DROPDOWN_ADDITIONAL_INPUT == uiType || UiType.RADIO_BUTTON_ADDITIONAL_INPUT == uiType) { latestCstic.setAdditionalValue(errorValue); } else { latestCstic.setValue(errorValue); }/*from w w w . j a v a 2s. co m*/ bindingResult.addError(fieldError); group.setGroupStatus(GroupStatusType.ERROR); } } final List<UiGroupData> subGroups = group.getSubGroups(); if (null == subGroups) { return; } for (final UiGroupData subGroup : subGroups) { restoreValidationErrorsInGroup(userInputToRestore, bindingResult, subGroup); } }
From source file:de.appsolve.padelcampus.admin.controller.bookings.AdminBookingsReservationsController.java
@Override public ModelAndView postEditView(@ModelAttribute("Model") ReservationRequest reservationRequest, HttpServletRequest request, BindingResult bindingResult) { ModelAndView addView = getAddView(reservationRequest); validator.validate(reservationRequest, bindingResult); if (bindingResult.hasErrors()) { return addView; }// ww w. j a v a 2 s. c o m try { Player player = sessionUtil.getUser(request); //calculate reservation bookings, taking into account holidays LocalDate date = reservationRequest.getStartDate(); LocalDate endDate = reservationRequest.getEndDate(); List<Booking> bookings = new ArrayList<>(); List<Booking> failedBookings = new ArrayList<>(); LocalDateTime blockingTime = new LocalDateTime(); while (date.compareTo(endDate) <= 0) { Set<CalendarWeekDay> calendarWeekDays = reservationRequest.getCalendarWeekDays(); for (CalendarWeekDay calendarWeekDay : calendarWeekDays) { if (calendarWeekDay.ordinal() + 1 == date.getDayOfWeek()) { try { List<CalendarConfig> calendarConfigs = calendarConfigDAO.findFor(date); //throws CalendarConfigException Iterator<CalendarConfig> iterator = calendarConfigs.iterator(); while (iterator.hasNext()) { CalendarConfig calendarConfig = iterator.next(); if (!bookingUtil.isHoliday(date, calendarConfig)) { for (Offer offer : reservationRequest.getOffers()) { Booking booking = new Booking(); booking.setAmount(BigDecimal.ZERO); booking.setBlockingTime(blockingTime); booking.setBookingDate(date); booking.setBookingTime(reservationRequest.getStartTime()); booking.setBookingType(BookingType.reservation); booking.setComment(reservationRequest.getComment()); booking.setConfirmed(Boolean.TRUE); booking.setCurrency(Currency.EUR); booking.setDuration(getDuration(reservationRequest, calendarConfig)); booking.setPaymentConfirmed(reservationRequest.getPaymentConfirmed()); booking.setPaymentMethod(PaymentMethod.Reservation); booking.setPlayer(player); booking.setUUID(BookingUtil.generateUUID()); booking.setOffer(offer); booking.setPublicBooking(reservationRequest.getPublicBooking()); //we call this inside the loop to prevent overbooking List<Booking> confirmedBookings = bookingDAO .findBlockedBookingsForDate(date); OfferDurationPrice offerDurationPrice = bookingUtil.getOfferDurationPrice( calendarConfigs, confirmedBookings, booking.getBookingDate(), booking.getBookingTime(), offer); if (offerDurationPrice == null) { failedBookings.add(booking); continue; } else { BigDecimal price = offerDurationPrice.getDurationPriceMap() .get(booking.getDuration().intValue()); booking.setAmount(price); } TimeSlot timeSlot = new TimeSlot(); timeSlot.setDate(date); timeSlot.setStartTime(reservationRequest.getStartTime()); timeSlot.setEndTime(reservationRequest.getEndTime()); timeSlot.setConfig(calendarConfig); Long bookingSlotsLeft = bookingUtil.getBookingSlotsLeft(timeSlot, offer, confirmedBookings); if (bookingSlotsLeft < 1) { failedBookings.add(booking); continue; } //we save the booking directly to prevent overbookings booking = bookingDAO.saveOrUpdate(booking); bookings.add(booking); } } break; } break; } catch (CalendarConfigException e) { LOG.warn( "Caught calendar config exception during add reservation request. This may be normal (for holidays)", e); Booking failedBooking = new Booking(); failedBooking.setPlayer(player); failedBooking.setBookingDate(date); failedBooking.setBookingTime(reservationRequest.getStartTime()); failedBookings.add(failedBooking); } } } date = date.plusDays(1); } if (!failedBookings.isEmpty()) { throw new Exception(msg.get("UnableToReserveAllDesiredTimes", new Object[] { StringUtils.join(bookings, "<br/>"), StringUtils.join(failedBookings, "<br/>") })); } if (bookings.isEmpty()) { throw new Exception(msg.get("NoCourtReservationsForSelectedDateTime")); } return new ModelAndView("redirect:/admin/bookings/reservations"); } catch (Exception e) { LOG.error(e, e); bindingResult.addError(new ObjectError("comment", e.getMessage())); return addView; } }
From source file:de.appsolve.padelcampus.admin.controller.bookings.AdminBookingsReservationsController.java
@RequestMapping(method = POST, value = "booking/{bookingId}") public ModelAndView postEditBooking(@PathVariable("bookingId") Long bookingId, @Valid @ModelAttribute("Model") ReservationRequest model, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return getEditView(model); }// w w w . j a v a2s.co m try { LocalDate today = new LocalDate(); LocalTime now = new LocalTime(); if (model.getStartDate().compareTo(today) < 0 || (model.getStartDate().equals(today) && model.getStartTime().compareTo(now) < 0)) { throw new Exception(msg.get("RequestedTimeIsInThePast")); } /* only one offer possible */ Offer offer = model.getOffers().iterator().next(); /* make sure to not modify booking before we know it can be changed b/c auf auto transaction commit */ Booking booking = bookingDAO.findById(bookingId); List<CalendarConfig> calendarConfigs = calendarConfigDAO.findFor(model.getStartDate()); //throws CalendarConfigException Iterator<CalendarConfig> iterator = calendarConfigs.iterator(); while (iterator.hasNext()) { CalendarConfig calendarConfig = iterator.next(); if (!bookingUtil.isHoliday(model.getStartDate(), calendarConfig)) { List<Booking> confirmedBookings = bookingDAO.findBlockedBookingsForDate(model.getStartDate()); //remove the current booking as we want to update it confirmedBookings.remove(booking); OfferDurationPrice offerDurationPrice = bookingUtil.getOfferDurationPrice(calendarConfigs, confirmedBookings, model.getStartDate(), model.getStartTime(), offer); if (offerDurationPrice != null) { TimeSlot timeSlot = new TimeSlot(); timeSlot.setDate(model.getStartDate()); timeSlot.setStartTime(model.getStartTime()); timeSlot.setEndTime(model.getEndTime()); timeSlot.setConfig(calendarConfig); Long bookingSlotsLeft = bookingUtil.getBookingSlotsLeft(timeSlot, offer, confirmedBookings); if (bookingSlotsLeft >= 1) { BigDecimal price = offerDurationPrice.getDurationPriceMap() .get(booking.getDuration().intValue()); booking.setAmount(price); booking.setBlockingTime(new LocalDateTime()); booking.setBookingDate(model.getStartDate()); booking.setBookingTime(model.getStartTime()); booking.setComment(model.getComment()); booking.setDuration(getDuration(model, calendarConfig)); booking.setOffer(offer); booking.setOfferOptions(model.getOfferOptions()); booking.setPaymentConfirmed(model.getPaymentConfirmed()); booking.setPaymentMethod(PaymentMethod.Reservation); booking.setPublicBooking(model.getPublicBooking()); bookingDAO.saveOrUpdate(booking); return redirectToIndex(); } } } } throw new Exception(msg.get("NoCourtReservationsForSelectedDateTime")); } catch (Exception e) { LOG.error(e); bindingResult.addError(new ObjectError("id", e.getMessage())); return getEditView(model); } }
From source file:de.appsolve.padelcampus.admin.controller.bookings.AdminBookingsSettingsController.java
@Override public ModelAndView postEditView(@ModelAttribute("Model") CalendarConfig config, HttpServletRequest request, BindingResult result) { //make sure no overlapping configurations are added List<CalendarConfig> existingConfigs = calendarConfigDAO.findAll(); for (CalendarConfig existingConfig : existingConfigs) { //skip self if (config.getId() == null || !config.getId().equals(existingConfig.getId())) { //make sure this config starts before the exising config ends (date) if (config.getStartDate().compareTo(existingConfig.getEndDate()) < 0) { //make sure this config ends after the existing config starts (date) if (config.getEndDate().compareTo(existingConfig.getStartDate()) > 0) { //make sure week day matches for (CalendarWeekDay weekDay : config.getCalendarWeekDays()) { for (CalendarWeekDay existingWeekDay : existingConfig.getCalendarWeekDays()) { if (weekDay.equals(existingWeekDay)) { //make sure this config starts before the existing config ends (time) if (config.getStartTime().compareTo(existingConfig.getEndTime()) < 0) { //make sure this config ends after the exising config starts (time) if (config.getEndTime().compareTo(existingConfig.getStartTime()) > 0) { //make sure offer matches for (Offer offer : config.getOffers()) { for (Offer existingOffer : existingConfig.getOffers()) { if (offer.equals(existingOffer)) { result.addError(new ObjectError("id", msg.get( "CannotAddCalendarConfigurationDueToOverlap"))); return super.postEditView(config, request, result); } } } }// w w w . j a va 2 s .c o m } } } } } } } } return super.postEditView(config, request, result); }
From source file:de.appsolve.padelcampus.admin.controller.bookings.AdminBookingsVoucherController.java
@Override @RequestMapping(value = { "add", "edit/{modelId}" }, method = POST) public ModelAndView postEditView(@ModelAttribute("Model") Voucher model, HttpServletRequest request, BindingResult result) { ModelAndView editView = getEditView(model); Integer voucherCount = Integer.parseInt(request.getParameter("voucherCount")); editView.addObject("voucherCount", voucherCount); validator.validate(model, result);//w ww. ja v a 2s . c om if (StringUtils.isEmpty(model.getComment())) { result.addError(new ObjectError("comment", msg.get("NotEmpty.comment"))); } if (!result.hasErrors()) { List<Voucher> vouchers = new ArrayList<>(); for (int i = 0; i < voucherCount; i++) { Voucher voucher = VoucherUtil.createNewVoucher(model); voucherDAO.saveOrUpdate(voucher); vouchers.add(voucher); } editView.addObject("Vouchers", vouchers); } return editView; }
From source file:de.appsolve.padelcampus.admin.controller.bookings.AdminBookingsVoucherController.java
@RequestMapping(value = { "send" }, method = POST) public ModelAndView postSendView(@ModelAttribute("Model") Voucher model, HttpServletRequest request, BindingResult result) { validator.validate(model, result);// www . j a va 2s . co m String[] eventIds = request.getParameterValues("events"); if (eventIds == null) { result.addError(new ObjectError("events", msg.get("NotEmpty.events"))); return getSendView(model); } if (!result.hasErrors()) { for (String eventId : eventIds) { Long id = Long.parseLong(eventId); Event event = eventDAO.findByIdFetchWithParticipantsAndPlayers(id); Map<Player, List<Game>> playerGameMap = new HashMap<>(); List<Game> eventGames = gameDAO.findByEvent(event); for (Game game : eventGames) { Voucher voucher = VoucherUtil.createNewVoucher(model); voucher.setComment(event.getName()); voucher.setGame(game); voucherDAO.saveOrUpdate(voucher); game.setVoucherUUID(voucher.getUUID()); gameDAO.saveOrUpdate(game); Set<Participant> participants = game.getParticipants(); for (Participant participant : participants) { if (participant instanceof Team) { Team team = (Team) participant; Set<Player> players = team.getPlayers(); for (Player player : players) { addGame(playerGameMap, player, game); } } else if (participant instanceof Player) { Player player = (Player) participant; addGame(playerGameMap, player, game); } } } for (Entry<Player, List<Game>> entry : playerGameMap.entrySet()) { Player player = entry.getKey(); List<Game> games = entry.getValue(); StringBuilder sb = new StringBuilder(); sb.append(msg.get("NewVoucherListEmailBodyStart", new Object[] { player.toString(), event.toString() })); for (Game game : games) { sb.append(game); sb.append(": "); sb.append(game.getVoucherUUID()); sb.append("\n"); } sb.append("\n\n"); sb.append(msg.get("NewVoucherListEmailBodyEnd", new Object[] { RequestUtil.getBaseURL(request) })); Mail mail = new Mail(); mail.addRecipient(player); mail.setSubject(event.getName()); mail.setBody(sb.toString()); try { mailUtils.send(mail, request); } catch (MailException | IOException ex) { LOG.error("Error while sending voucher list to " + player.getEmail(), ex); } } } } return redirectToIndex(request); }
From source file:de.appsolve.padelcampus.admin.controller.events.AdminEventsController.java
@Override @RequestMapping(value = { "add", "edit/{modelId}" }, method = POST) public ModelAndView postEditView(@ModelAttribute("Model") Event model, HttpServletRequest request, BindingResult result) { ModelAndView editView = getEditView(model); validator.validate(model, result);//from w ww . jav a2 s .c om if (result.hasErrors()) { return editView; } try { if (model.getId() != null) { //prevent removal of a team if it has already played a game Event existingEvent = eventDAO.findByIdFetchWithParticipants(model.getId()); if (!existingEvent.getParticipants().equals(model.getParticipants())) { for (Participant participant : existingEvent.getParticipants()) { if (!model.getParticipants().contains(participant)) { List<Game> existingGames = gameDAO.findByParticipantAndEventWithScoreOnly(participant, model); if (!existingGames.isEmpty()) { throw new Exception( msg.get("TeamHasAlreadyPlayedInEvent", new Object[] { participant.toString(), existingGames.size(), model.toString() }), null); } } } } //prevent switching from one event type to another if (!existingEvent.getEventType().equals(model.getEventType())) { throw new Exception(msg.get("CannotModifyEventTypeOfExistingEvent")); } } //make sure end date is not before start date if (model.getEndDate().isBefore(model.getStartDate())) { model.setEndDate(model.getStartDate()); } //if participants can sign up online, make sure price and payment methods are set if (model.getAllowSignup()) { if (model.getPaymentMethods() == null || model.getPaymentMethods().isEmpty()) { throw new Exception(msg.get("SelectAPaymentMethod")); } if (model.getPrice() == null) { throw new Exception(msg.get("SetAPrice")); } } switch (model.getEventType()) { case SingleRoundRobin: model = getDAO().saveOrUpdate(model); //remove games that have not been played yet gameUtil.removeObsoleteGames(model); gameUtil.createMissingGames(model, model.getParticipants()); return redirectToIndex(request); case GroupTwoRounds: //remove games that have not been played yet gameUtil.removeObsoleteGames(model); //no break case GroupKnockout: model = getDAO().saveOrUpdate(model); if (!model.getParticipants().isEmpty()) { return redirectToGroupDraws(model); } else { return redirectToIndex(request); } case Knockout: model = getDAO().saveOrUpdate(model); if (!model.getParticipants().isEmpty()) { return redirectToDraws(model); } else { return redirectToIndex(request); } case CommunityRoundRobin: case PullRoundRobin: case FriendlyGames: getDAO().saveOrUpdate(model); return redirectToIndex(request); default: throw new Exception("Unsupported event type " + model.getEventType()); } } catch (Exception e) { result.addError(new ObjectError("id", e.getMessage())); return editView; } }
From source file:de.appsolve.padelcampus.admin.controller.events.AdminEventsController.java
@RequestMapping(method = POST, value = "event/{eventId}/groupgamesend") public ModelAndView saveEventGroupGamesEnd(@PathVariable("eventId") Long eventId, @ModelAttribute("Model") Event dummy, BindingResult result) { Event event = eventDAO.findByIdFetchWithParticipantsAndGames(eventId); try {//from ww w . j av a 2 s . c o m SortedMap<Integer, List<Game>> roundGames = eventsUtil.getRoundGameMap(event); if (!roundGames.isEmpty()) { throw new Exception(msg.get("GroupGamesAlreadyEnded")); } SortedMap<Integer, List<Game>> groupGames = eventsUtil.getGroupGameMap(event); if (groupGames.isEmpty()) { throw new Exception(msg.get("NoGroupGames")); } List<Participant> rankedParticipants = getRankedGroupParticipants(groupGames, event.getNumberOfGroups(), event.getNumberOfWinnersPerGroup()); eventsUtil.createKnockoutGames(event, rankedParticipants); return redirectToDraws(event); } catch (Exception e) { result.addError(new ObjectError("*", e.getMessage())); return getGroupGamesEndView(dummy); } }