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:nl.surfnet.coin.teams.control.AddMemberController.java

/**
 * Called after submitting the add members form
 *
 * @param form     {@link nl.surfnet.coin.teams.domain.InvitationForm} from the session
 * @param result   {@link org.springframework.validation.BindingResult}
 * @param request  {@link javax.servlet.http.HttpServletRequest}
 * @param modelMap {@link org.springframework.ui.ModelMap}
 * @return the name of the form if something is wrong
 *         before handling the invitation,
 *         otherwise a redirect to the detailteam url
 * @throws IOException if something goes wrong handling the invitation
 *//*ww w  .jav  a 2 s  .  c  o  m*/
@RequestMapping(value = "/doaddmember.shtml", method = RequestMethod.POST)
public String addMembersToTeam(@ModelAttribute(TokenUtil.TOKENCHECK) String sessionToken,
        @ModelAttribute("invitationForm") InvitationForm form, BindingResult result, HttpServletRequest request,
        @RequestParam() String token, SessionStatus status, ModelMap modelMap) throws IOException {
    TokenUtil.checkTokens(sessionToken, token, status);
    Person person = (Person) request.getSession().getAttribute(LoginInterceptor.PERSON_SESSION_KEY);
    addNewMemberRolesToModelMap(person, form.getTeamId(), modelMap);

    final boolean isAdminOrManager = controllerUtil.hasUserAdministrativePrivileges(person,
            request.getParameter(TEAM_PARAM));
    if (!isAdminOrManager) {
        status.setComplete();
        throw new RuntimeException("Requester (" + person.getId()
                + ") is not member or does not have the correct " + "privileges to add (a) member(s)");
    }
    final boolean isAdmin = controllerUtil.hasUserAdminPrivileges(person, request.getParameter(TEAM_PARAM));
    // if a non admin tries to add a role admin or manager -> make invitation for member
    if (!(isAdmin || Role.Member.equals(form.getIntendedRole()))) {
        form.setIntendedRole(Role.Member);
    }
    Validator validator = new InvitationFormValidator();
    validator.validate(form, result);

    if (result.hasErrors()) {
        modelMap.addAttribute(TEAM_PARAM, controllerUtil.getTeamById(form.getTeamId()));
        return "addmember";
    }

    // Parse the email addresses to see whether they are valid
    InternetAddress[] emails;
    try {
        emails = InternetAddress.parse(getAllEmailAddresses(form));
    } catch (AddressException e) {
        result.addError(new FieldError("invitationForm", "emails", "error.wrongFormattedEmailList"));
        return "addmember";
    }

    Locale locale = localeResolver.resolveLocale(request);
    doInviteMembers(emails, form, locale);
    AuditLog.log("User {} sent invitations for team {}, with role {} to addresses: {}", person.getId(),
            form.getTeamId(), form.getIntendedRole(), emails);

    status.setComplete();
    modelMap.clear();
    return "redirect:detailteam.shtml?team=" + URLEncoder.encode(form.getTeamId(), UTF_8) + "&view="
            + ViewUtil.getView(request);
}

From source file:com.devnexus.ting.web.controller.cfp.CallForPapersController.java

/**
 * Add a new Abstract//from w  w  w  .  j a v  a 2  s.co m
 *
 * @param cfpSubmission
 * @param bindingResult
 * @param model
 * @param request
 * @param redirectAttributes
 * @return
 */
@RequestMapping(value = "/abstract", method = RequestMethod.POST)
public String addCfp(@Valid @ModelAttribute("cfpSubmission") CfpSubmissionForm cfpSubmission,
        BindingResult bindingResult, ModelMap model, HttpServletRequest request,
        RedirectAttributes redirectAttributes) {

    if (CfpSettings.CfpState.CLOSED.equals(cfpSettings.getState())) {
        return "redirect:/s/index";
    }

    if (request.getParameter("cancel") != null) {
        return "redirect:/s/cfp/index";
    }

    final Event eventFromDb = businessService.getCurrentEvent();

    if (bindingResult.hasErrors()) {
        prepareReferenceData(model);
        final User user = (User) userService.loadUserByUsername(securityFacade.getUsername());
        final List<CfpSubmissionSpeaker> cfpSubmissionSpeakers = businessService
                .getCfpSubmissionSpeakersForUserAndEvent(user, eventFromDb);
        model.addAttribute("speakers", cfpSubmissionSpeakers);
        return "cfp/cfp";
    }

    final CfpSubmission cfpSubmissionToSave = new CfpSubmission();

    if (cfpSubmission.getCfpSubmissionSpeakers() == null
            || cfpSubmission.getCfpSubmissionSpeakers().size() < 1) {
        ObjectError error = new ObjectError("error", "Please submit at least 1 speaker.");
        bindingResult.addError(error);
        prepareReferenceData(model);

        final User user = (User) userService.loadUserByUsername(securityFacade.getUsername());
        final List<CfpSubmissionSpeaker> cfpSubmissionSpeakers = businessService
                .getCfpSubmissionSpeakersForUserAndEvent(user, eventFromDb);
        model.addAttribute("speakers", cfpSubmissionSpeakers);
        return "cfp/cfp";
    }

    cfpSubmissionToSave.setDescription(cfpSubmission.getDescription());
    cfpSubmissionToSave.setEvent(eventFromDb);

    cfpSubmissionToSave.setPresentationType(cfpSubmission.getPresentationType());
    cfpSubmissionToSave.setSessionRecordingApproved(cfpSubmission.isSessionRecordingApproved());
    cfpSubmissionToSave.setSkillLevel(cfpSubmission.getSkillLevel());
    cfpSubmissionToSave.setSlotPreference(cfpSubmission.getSlotPreference());
    cfpSubmissionToSave.setTitle(cfpSubmission.getTitle());
    cfpSubmissionToSave.setTopic(cfpSubmission.getTopic());
    cfpSubmissionToSave.setStatus(CfpSubmissionStatusType.PENDING);

    final User user = (User) userService.loadUserByUsername(securityFacade.getUsername());
    final List<CfpSubmissionSpeaker> cfpSubmissionSpeakersFromDb = businessService
            .getCfpSubmissionSpeakersForUserAndEvent(user, eventFromDb);

    for (CfpSubmissionSpeaker cfpSubmissionSpeaker : cfpSubmission.getCfpSubmissionSpeakers()) {
        for (CfpSubmissionSpeaker cfpSubmissionSpeakerFromDb : cfpSubmissionSpeakersFromDb) {
            if (cfpSubmissionSpeakerFromDb.getId().equals(cfpSubmissionSpeaker.getId())) {
                cfpSubmissionToSave.getCfpSubmissionSpeakers().add(cfpSubmissionSpeakerFromDb);
            }
        }
    }

    cfpSubmissionToSave.setCreatedByUser(user);

    LOGGER.info(cfpSubmissionToSave.toString());
    businessService.saveAndNotifyCfpSubmission(cfpSubmissionToSave);

    redirectAttributes.addFlashAttribute("successMessage",
            String.format("Your abstract '%s' was added successfully.", cfpSubmissionToSave.getTitle()));
    return "redirect:/s/cfp/index";
}

From source file:com.stormpath.tooter.controller.LoginController.java

@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("customer") User customer, BindingResult result,
        SessionStatus status, HttpSession session) {

    loginValidator.validate(customer, result);

    String returnStr = "login";

    if (!result.hasErrors()) {

        try {/*from w w w . j a va  2 s .c  o m*/

            // For authentication the only thing we need to do is call Application.authenticate(),
            // instantiating the proper AuthenticationRequest (UsernamePasswordRequest in this case),
            // providing the account's credentials.
            AuthenticationRequest request = new UsernamePasswordRequest(customer.getUserName(),
                    customer.getPassword());
            AuthenticationResult authcResult = stormpath.getApplication().authenticateAccount(request);

            Account account = authcResult.getAccount();

            User user = new User(account);

            // If the customer queried from the database does not exist
            // we create it in the application's internal database,
            // so we don't have to go through the process of signing a user up
            // that has already been authenticated in the previous call to the Stormpath API.
            // This is because the application uses an in-memory database (HSQLDB)
            // that only persists while the application is up.
            User dbCustomer = customerDao.getCustomerByUserName(customer.getUserName());
            if (dbCustomer == null) {
                customerDao.saveCustomer(user);
            }

            if (dbCustomer != null) {
                user.setId(dbCustomer.getId());
            }

            session.setAttribute("sessionUser", user);
            session.setAttribute("permissionUtil", permissionUtil);

            returnStr = "redirect:/tooter";

            status.setComplete();
        } catch (ResourceException re) {
            result.addError(new ObjectError("userName", re.getMessage()));
            re.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return returnStr;
}

From source file:com.devnexus.ting.web.controller.admin.RegistrationController.java

@RequestMapping(value = "/s/admin/{eventKey}/uploadRegistration", method = RequestMethod.POST)
public ModelAndView uploadGroupRegistration(ModelAndView model, HttpServletRequest request,
        @PathVariable(value = "eventKey") String eventKey,
        @Valid @ModelAttribute("registerForm") UploadGroupRegistrationForm uploadForm,
        BindingResult bindingResult) throws FileNotFoundException, IOException, InvalidFormatException {

    EventSignup signUp = eventSignupRepository.getByEventKey(eventKey);
    model.getModelMap().addAttribute("event", signUp.getEvent());

    if (bindingResult.hasErrors()) {

        model.getModelMap().addAttribute("registerForm", uploadForm);
        model.setViewName("/admin/upload-registration");
    } else {//w  w w.ja  v  a2  s  .c o m

        boolean hasErrors = false;

        try {

            Workbook wb = WorkbookFactory.create(uploadForm.getRegistrationFile().getInputStream());
            Sheet sheet = wb.getSheetAt(0);
            Cell contactNameCell = sheet.getRow(0).getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            Cell contactEmailCell = sheet.getRow(1).getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            Cell contactPhoneCell = sheet.getRow(2).getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            Cell registrationReferenceCell = sheet.getRow(3).getCell(1,
                    Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);

            if (contactNameCell.getStringCellValue().isEmpty()) {
                hasErrors = true;
                bindingResult.addError(new ObjectError("registrationFile", "Contact Name Empty"));
            }

            if (contactEmailCell.getStringCellValue().isEmpty()) {
                hasErrors = true;
                bindingResult.addError(new ObjectError("registrationFile", "Contact Email Empty"));
            }

            if (contactPhoneCell.getStringCellValue().isEmpty()) {
                hasErrors = true;
                bindingResult.addError(new ObjectError("registrationFile", "Contact Phone Empty"));
            }

            if (registrationReferenceCell.getStringCellValue().isEmpty()) {
                hasErrors = true;
                bindingResult.addError(new ObjectError("registrationFile", "Registration Reference Empty"));
            }

            if (!hasErrors) {
                RegistrationDetails details = new RegistrationDetails();
                details.setContactEmailAddress(contactEmailCell.getStringCellValue());
                details.setContactName(contactNameCell.getStringCellValue());
                details.setContactPhoneNumber(contactPhoneCell.getStringCellValue());
                details.setRegistrationFormKey(registrationReferenceCell.getStringCellValue());
                details.setEvent(signUp.getEvent());
                details.setFinalCost(BigDecimal.ZERO);
                details.setInvoice("Invoiced");
                details.setPaymentState(RegistrationDetails.PaymentState.PAID);
                int attendeeRowIndex = 7;

                Row attendeeRow = sheet.getRow(attendeeRowIndex);
                while (attendeeRow != null) {
                    attendeeRow = sheet.getRow(attendeeRowIndex);
                    if (attendeeRow != null) {
                        Cell firstName = attendeeRow.getCell(0, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell lastName = attendeeRow.getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell emailAddress = attendeeRow.getCell(2, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell city = attendeeRow.getCell(3, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell state = attendeeRow.getCell(4, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell country = attendeeRow.getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell ticketType = attendeeRow.getCell(6, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell company = attendeeRow.getCell(7, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell jobTitle = attendeeRow.getCell(8, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell tshirtSize = attendeeRow.getCell(9, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell vegetarian = attendeeRow.getCell(10, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        Cell sponsorMessages = attendeeRow.getCell(11,
                                Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);

                        if (firstName.getStringCellValue().isEmpty()) {
                            break;
                        }

                        if (lastName.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information : lastName"));
                            hasErrors = true;
                            break;
                        }
                        if (emailAddress.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information : emailAddress"));
                            hasErrors = true;
                            break;
                        }
                        if (city.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information : city"));
                            hasErrors = true;
                            break;
                        }
                        if (state.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information : state "));
                            hasErrors = true;
                            break;
                        }
                        if (country.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information : country"));
                            hasErrors = true;
                            break;
                        }
                        if (company.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information : company"));
                            hasErrors = true;
                            break;
                        }
                        if (jobTitle.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information : jobTitle"));
                            hasErrors = true;
                            break;
                        }

                        if (ticketType.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information: ticket type"));
                            hasErrors = true;
                            break;
                        }

                        if (tshirtSize.getStringCellValue().isEmpty()) {
                            bindingResult.addError(new ObjectError("registrationFile",
                                    " row " + (attendeeRowIndex + 1) + " missing information: t shirt "));
                            hasErrors = true;
                            break;
                        }
                        if (vegetarian.getStringCellValue().isEmpty()
                                || !(vegetarian.getStringCellValue().equalsIgnoreCase("no")
                                        || vegetarian.getStringCellValue().equalsIgnoreCase("yes"))) {
                            bindingResult.addError(
                                    new ObjectError("registrationFile", " row " + (attendeeRowIndex + 1)
                                            + " missing information. Vegetarian option should be yes or no "));
                            hasErrors = true;
                            break;
                        }
                        if (sponsorMessages.getStringCellValue().isEmpty()
                                || !(sponsorMessages.getStringCellValue().equalsIgnoreCase("no")
                                        || sponsorMessages.getStringCellValue().equalsIgnoreCase("yes"))) {
                            bindingResult.addError(
                                    new ObjectError("registrationFile", " row " + (attendeeRowIndex + 1)
                                            + " missing information. Sponsor message should be yes or no "));
                            hasErrors = true;
                            break;
                        }

                        TicketOrderDetail detail = new TicketOrderDetail();

                        detail.setCity(city.getStringCellValue());
                        detail.setCompany(company.getStringCellValue());
                        detail.setCouponCode("");
                        detail.setCountry(country.getStringCellValue());
                        detail.setEmailAddress(emailAddress.getStringCellValue());
                        detail.setFirstName(firstName.getStringCellValue());
                        detail.setJobTitle(jobTitle.getStringCellValue());
                        detail.setLastName(lastName.getStringCellValue());
                        detail.setSponsorMayContact(
                                sponsorMessages.getStringCellValue().equalsIgnoreCase("no") ? "false" : "true");
                        detail.setState(state.getStringCellValue());
                        detail.setTicketGroup(
                                Long.parseLong(ticketType.getStringCellValue().split("-\\|-")[1].trim()));

                        detail.setLabel(businessService.getTicketGroup(detail.getTicketGroup()).getLabel());

                        detail.settShirtSize(tshirtSize.getStringCellValue());
                        detail.setVegetarian(
                                vegetarian.getStringCellValue().equalsIgnoreCase("no") ? "false" : "true");
                        detail.setRegistration(details);
                        details.getOrderDetails().add(detail);

                        attendeeRowIndex++;

                    }
                }

                if (uploadForm.getOverrideRegistration()) {
                    try {
                        RegistrationDetails tempRegistration = businessService
                                .getRegistrationForm(registrationReferenceCell.getStringCellValue());
                        tempRegistration.getOrderDetails().forEach((oldDetail) -> {
                            oldDetail.setRegistration(null);
                        });
                        tempRegistration.getOrderDetails().clear();
                        tempRegistration.getOrderDetails().addAll(details.getOrderDetails());

                        tempRegistration.getOrderDetails().forEach((detail) -> {
                            detail.setRegistration(tempRegistration);
                        });
                        details = tempRegistration;

                        businessService.updateRegistration(details, uploadForm.getSendEmail());
                    } catch (EmptyResultDataAccessException ignore) {
                        businessService.updateRegistration(details, uploadForm.getSendEmail());
                    }
                } else {
                    try {
                        RegistrationDetails tempRegistration = businessService
                                .getRegistrationForm(registrationReferenceCell.getStringCellValue());
                        hasErrors = true;
                        bindingResult.addError(new ObjectError("registrationFile",
                                "Registration with this key exists, please check \"Replace Registrations\"."));
                    } catch (EmptyResultDataAccessException ignore) {
                        businessService.updateRegistration(details, uploadForm.getSendEmail());
                    }
                }

            }

        } catch (Exception ex) {
            hasErrors = true;
            Logger.getAnonymousLogger().log(Level.SEVERE, ex.getMessage(), ex);

            bindingResult.addError(new ObjectError("registrationFile", ex.getMessage()));
        }
        if (hasErrors) {
            model.setViewName("/admin/upload-registration");
        } else {
            model.setViewName("/admin/index");
        }
    }

    return model;
}

From source file:com.devnexus.ting.web.controller.cfp.CallForPapersController.java

@RequestMapping(value = "/speaker/{cfpSubmissionSpeakerId}", method = RequestMethod.POST)
public String editCfpSpeaker(@PathVariable("cfpSubmissionSpeakerId") Long cfpSubmissionSpeakerId,
        @Valid @ModelAttribute("cfpSubmissionSpeaker") CfpSubmissionSpeakerForm cfpSubmissionSpeaker,
        BindingResult bindingResult, ModelMap model, RedirectAttributes redirectAttributes,
        HttpServletRequest request) {// w ww  .  j  av a  2s.  com

    if (request.getParameter("cancel") != null) {
        return "redirect:/s/cfp/index";
    }

    final User user = (User) userService.loadUserByUsername(securityFacade.getUsername());
    final Event event = businessService.getCurrentEvent();
    if (request.getParameter("delete") != null) {

        final List<CfpSubmission> cfpSubmissions = businessService
                .getCfpSubmissionsForUserAndEvent(user.getId(), event.getId());

        boolean canDelete = true;

        for (CfpSubmission cfpSubmission : cfpSubmissions) {
            for (CfpSubmissionSpeaker speaker : cfpSubmission.getCfpSubmissionSpeakers()) {
                if (speaker.getId().equals(cfpSubmissionSpeakerId)) {
                    canDelete = false;
                    break;
                }
            }
        }

        if (canDelete) {
            businessService.deleteCfpSubmissionSpeakerForUser(cfpSubmissionSpeakerId, event.getId(),
                    user.getId());
        } else {
            bindingResult.addError(new ObjectError("cfpSubmissionSpeaker",
                    "Cannot delete speaker. The speaker is still associated with an abstract."));
            prepareReferenceData(model);
            return "/cfp/edit-cfp-speaker";
        }
        redirectAttributes.addFlashAttribute("successMessage", String
                .format("The speaker '%s' was deleted successfully.", cfpSubmissionSpeaker.getFirstLastName()));
        return "redirect:/s/cfp/index";
    }

    if (!cfpSubmissionSpeaker.isAvailableEntireEvent()) {
        int index = 0;
        for (CfpAvailabilityForm availabilityForm : cfpSubmissionSpeaker.getAvailabilityDays()) {

            if (availabilityForm.getAvailabilitySelection() == null) {
                bindingResult.addError(new FieldError("cfpSubmissionSpeaker",
                        "availabilityDays[" + index++ + "].availabilitySelection",
                        "Please make a selection regarding your availability."));
            }

            if (CfpSpeakerAvailability.PARTIAL_AVAILABILITY
                    .equals(availabilityForm.getAvailabilitySelection())) {
                if (availabilityForm.getStartTime() == null) {
                    bindingResult.addError(new FieldError("cfpSubmissionSpeaker",
                            "availabilityDays[" + index + "].startTime", "Please provide a start time."));
                }
                if (availabilityForm.getEndTime() == null) {
                    bindingResult.addError(new FieldError("cfpSubmissionSpeaker",
                            "availabilityDays[" + index + "].endTime", "Please provide an end time."));
                }

                if (availabilityForm.getStartTime() != null && availabilityForm.getEndTime() != null
                        && !availabilityForm.getStartTime().isBefore(availabilityForm.getEndTime())) {
                    bindingResult.addError(
                            new FieldError("cfpSubmissionSpeaker", "availabilityDays[" + index + "].endTime",
                                    "Please ensure that the end time is after the start time."));
                }
            }
            index++;
        }
    }

    if (bindingResult.hasErrors()) {
        prepareReferenceData(model);
        return "/cfp/edit-cfp-speaker";
    }

    final MultipartFile picture = cfpSubmissionSpeaker.getPictureFile();

    final CfpSpeakerImage cfpSpeakerImage = processPicture(picture, bindingResult);

    if (bindingResult.hasErrors()) {
        prepareReferenceData(model);
        return "/cfp/edit-cfp-speaker";
    }
    //FIXME
    final CfpSubmissionSpeaker cfpSubmissionSpeakerFromDb = businessService
            .getCfpSubmissionSpeakerWithPicture(cfpSubmissionSpeakerId);

    cfpSubmissionSpeakerFromDb.setEmail(cfpSubmissionSpeaker.getEmail());
    cfpSubmissionSpeakerFromDb.setCompany(cfpSubmissionSpeaker.getCompany());
    cfpSubmissionSpeakerFromDb.setBio(cfpSubmissionSpeaker.getBio());
    cfpSubmissionSpeakerFromDb.setFirstName(cfpSubmissionSpeaker.getFirstName());
    cfpSubmissionSpeakerFromDb.setGithubId(cfpSubmissionSpeaker.getGithubId());
    cfpSubmissionSpeakerFromDb.setGooglePlusId(cfpSubmissionSpeaker.getGooglePlusId());
    cfpSubmissionSpeakerFromDb.setLanyrdId(cfpSubmissionSpeaker.getLanyrdId());
    cfpSubmissionSpeakerFromDb.setLastName(cfpSubmissionSpeaker.getLastName());
    cfpSubmissionSpeakerFromDb.setPhone(cfpSubmissionSpeaker.getPhone());
    cfpSubmissionSpeakerFromDb.setLinkedInId(cfpSubmissionSpeaker.getLinkedInId());
    cfpSubmissionSpeakerFromDb.setTwitterId(cfpSubmissionSpeaker.getTwitterId());
    cfpSubmissionSpeakerFromDb.setLocation(cfpSubmissionSpeaker.getLocation());
    cfpSubmissionSpeakerFromDb.setMustReimburseTravelCost(cfpSubmissionSpeaker.isMustReimburseTravelCost());
    cfpSubmissionSpeakerFromDb.setTshirtSize(cfpSubmissionSpeaker.getTshirtSize());

    final List<CfpSubmissionSpeakerConferenceDay> cfpSubmissionSpeakerConferenceDays = new ArrayList<>();

    if (cfpSubmissionSpeaker.isAvailableEntireEvent()) {
        cfpSubmissionSpeakerFromDb.setAvailableEntireEvent(cfpSubmissionSpeaker.isAvailableEntireEvent());
    } else {

        cfpSubmissionSpeakerFromDb.setAvailableEntireEvent(cfpSubmissionSpeaker.isAvailableEntireEvent());

        final SortedSet<ConferenceDay> conferenceDays = event.getConferenceDays();

        for (CfpAvailabilityForm availabilityForm : cfpSubmissionSpeaker.getAvailabilityDays()) {
            ConferenceDay conferenceDayToUse = null;
            for (ConferenceDay conferenceDay : conferenceDays) {
                if (conferenceDay.getId().equals(availabilityForm.getConferenceDay().getId())) {
                    conferenceDayToUse = conferenceDay;
                }
            }
            if (conferenceDayToUse == null) {
                throw new IllegalStateException(
                        "Did not find conference day for id " + availabilityForm.getConferenceDay().getId());
            }
            System.out.println(conferenceDayToUse.getId());
            final CfpSubmissionSpeakerConferenceDay conferenceDay = new CfpSubmissionSpeakerConferenceDay();

            conferenceDay.setConferenceDay(conferenceDayToUse);
            conferenceDay.setCfpSubmissionSpeaker(cfpSubmissionSpeakerFromDb);
            if (CfpSpeakerAvailability.ANY_TIME.equals(availabilityForm.getAvailabilitySelection())) {
                conferenceDay.setCfpSpeakerAvailability(CfpSpeakerAvailability.ANY_TIME);
            } else if (CfpSpeakerAvailability.NO_AVAILABILITY
                    .equals(availabilityForm.getAvailabilitySelection())) {
                conferenceDay.setCfpSpeakerAvailability(CfpSpeakerAvailability.NO_AVAILABILITY);
            } else if (CfpSpeakerAvailability.PARTIAL_AVAILABILITY
                    .equals(availabilityForm.getAvailabilitySelection())) {
                conferenceDay.setCfpSpeakerAvailability(CfpSpeakerAvailability.PARTIAL_AVAILABILITY);
                conferenceDay.setStartTime(availabilityForm.getStartTime());
                conferenceDay.setEndTime(availabilityForm.getEndTime());
            }
            cfpSubmissionSpeakerConferenceDays.add(conferenceDay);
        }
    }

    if (cfpSpeakerImage != null) {
        cfpSubmissionSpeakerFromDb.setCfpSpeakerImage(cfpSpeakerImage);
    }

    businessService.saveCfpSubmissionSpeaker(cfpSubmissionSpeakerFromDb, cfpSubmissionSpeakerConferenceDays);

    redirectAttributes.addFlashAttribute("successMessage", String.format(
            "The speaker '%s' was edited successfully.", cfpSubmissionSpeakerFromDb.getFirstLastName()));
    return "redirect:/s/cfp/index";
}

From source file:com.br.uepb.validator.adapter.CustomConstraintSpringValidatorAdapter.java

@Override
protected void processConstraintViolations(Set<ConstraintViolation<Object>> violations, Errors errors) {
    for (ConstraintViolation<Object> violation : violations) {
        String field = violation.getPropertyPath().toString();
        FieldError fieldError = errors.getFieldError(field);
        if (fieldError == null || !fieldError.isBindingFailure()) {
            try {
                String errorCode = violation.getConstraintDescriptor().getAnnotation().annotationType()
                        .getSimpleName();
                Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field,
                        violation.getConstraintDescriptor());
                if (errors instanceof BindingResult) {
                    // can do custom FieldError registration with invalid value from ConstraintViolation,
                    // as necessary for Hibernate Validator compatibility (non-indexed set path in field)
                    BindingResult bindingResult = (BindingResult) errors;
                    String[] errorCodes = bindingResult.resolveMessageCodes(errorCode, field);
                    String nestedField = bindingResult.getNestedPath() + field;
                    ObjectError error;/*from ww  w .j a v  a2 s . c o m*/
                    if ("".equals(nestedField)) {
                        error = new ObjectError(errors.getObjectName(), errorCodes, errorArgs,
                                violation.getMessage());
                    } else {
                        Object invalidValue = violation.getInvalidValue();
                        if (!"".equals(field) && invalidValue == violation.getLeafBean()) {
                            // bean constraint with property path: retrieve the actual property value
                            invalidValue = bindingResult.getRawFieldValue(field);
                        }
                        if (violation.getMessage() != null && violation.getMessage().startsWith("{")
                                && violation.getMessage().endsWith("}")) {
                            String keyMessage = violation.getMessage();
                            keyMessage = keyMessage.replace("{", "");
                            keyMessage = keyMessage.replace("}", "");
                            List<String> temp = new ArrayList<String>(Arrays.asList(errorCodes));
                            temp.add(keyMessage);
                            errorCodes = temp.toArray(new String[temp.size()]);
                            error = new FieldError(errors.getObjectName(), nestedField, invalidValue, false,
                                    errorCodes, errorArgs, violation.getMessage());
                        } else {
                            error = new FieldError(errors.getObjectName(), nestedField, invalidValue, false,
                                    errorCodes, errorArgs, violation.getMessage());
                        }
                    }
                    bindingResult.addError(error);
                } else {
                    // got no BindingResult - can only do standard rejectValue call
                    // with automatic extraction of the current field value
                    if (violation.getMessage() != null && violation.getMessage().startsWith("{")
                            && violation.getMessage().endsWith("}")) {
                        String keyMessage = violation.getMessage();
                        keyMessage = keyMessage.replace("{", "");
                        keyMessage = keyMessage.replace("}", "");
                        errors.rejectValue(field, keyMessage);
                    } else {
                        errors.rejectValue(field, errorCode, errorArgs, violation.getMessage());
                    }
                }
            } catch (NotReadablePropertyException ex) {
                throw new IllegalStateException("JSR-303 validated property '" + field
                        + "' does not have a corresponding accessor for Spring data binding - "
                        + "check your DataBinder's configuration (bean property versus direct field access)",
                        ex);
            }
        }
    }
}

From source file:com.stormpath.tooter.controller.ProfileController.java

@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("user") User user, BindingResult result, SessionStatus status,
        HttpSession session, ModelMap model) {

    model.addAttribute("ADMINISTRATOR_URL", administratorGroupURL);
    model.addAttribute("PREMIUM_URL", premiumGroupURL);

    profileValidator.validate(user, result);

    if (!result.hasErrors()) {

        try {//from w  w w .j  a  v a2s. c  o  m

            // For account update, we just retrieve the current account and
            // call Account.save() after setting the modified properties.
            // An account can also be retrieved from the DataStore,
            // like the way we do it to get an Application or Directory object,
            // if the account's Rest URL is known to the application.

            User sessionUser = (User) session.getAttribute("sessionUser");
            Account account = sessionUser.getAccount();
            account.setGivenName(user.getFirstName());
            account.setSurname(user.getLastName());
            account.setEmail(user.getEmail());
            account.setUsername(user.getFirstName().toLowerCase() + user.getLastName().toLowerCase());

            String existingGroupUrl = null;
            if (account.getGroupMemberships().iterator().hasNext()) {
                GroupMembership groupMembership = account.getGroupMemberships().iterator().next();
                existingGroupUrl = groupMembership.getGroup().getHref();
                if (!existingGroupUrl.equals(user.getGroupUrl())) {
                    groupMembership.delete();
                    existingGroupUrl = null;
                }
            }

            if (user.getGroupUrl() != null && !user.getGroupUrl().isEmpty() && existingGroupUrl == null) {
                account.addGroup(stormpath.getDataStore().getResource(user.getGroupUrl(), Group.class));
            }

            account.save();

            user.setAccount(account);
            user.setUserName(sessionUser.getUserName());
            user.setTootList(sessionUser.getTootList());

            model.addAttribute("messageKey", "updated");
            model.addAttribute("user", user);
        } catch (ResourceException re) {
            ObjectError error = new ObjectError("user", re.getMessage());
            result.addError(error);
            re.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        status.setComplete();
    }
    return "profile";
}

From source file:com.virtusa.akura.common.controller.ForgotPasswordController.java

/**
 * The user enter his/her username in the given field and click submit to get a new password.
 * //w  ww .  j  a  v a2  s.  c  om
 * @param userLogin - set the UserLogin object.
 * @param bindingResult - bind the results to the model.
 * @param modMap - ModelMap to get view.
 * @param session - HttpSession.
 * @return - the name of the view.
 * @throws AkuraAppException - throws AkuraAppException if fail.
 */
@RequestMapping(value = SUBMIT_USERNAME_HTM, method = RequestMethod.POST)
public String onSubmit(@ModelAttribute(USER_LOGIN) UserLogin userLogin, BindingResult bindingResult,
        ModelMap modMap, HttpSession session) throws AkuraAppException {

    String error = null;
    String mailError = null;

    // Validate the Username.
    forgotPasswordValidator.validate(userLogin, bindingResult);

    if (bindingResult.hasErrors()) {
        return FROM_FORGOT_PASSWORD;
    }

    // Get the Username from the userlogin object.
    String userName = userLogin.getUsername().trim();

    UserLogin user = userService.getUser(userName);

    if (user == null) {

        error = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.USERNAME_ERROR);

    } else if (user.getLoginAttempts() == AkuraConstant.PARAM_INDEX_THREE) {

        error = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.USER_BLOCKED_ERROR);

    } else if (!userService.isSecurityQuestionsExist(user)) {

        error = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.NO_ANSWERS_ERROR);

    }

    if (user != null && user.getLoginAttempts() != AkuraConstant.PARAM_INDEX_THREE
            && userService.isSecurityQuestionsExist(user)) {

        session.setAttribute(USER_LOGIN_BY_NAME, user);
        List<UserSecurityQuestions> userSecurityQuestions = userService
                .getUserSecurityQuestionsById(user.getUserLoginId());

        WrapperSecurityQuestions submitAnswers = new WrapperSecurityQuestions();
        UserSecurityQuestions userQuestionOne = userSecurityQuestions.get(AkuraConstant.PARAM_INDEX_ZERO);
        UserSecurityQuestions userQuestionTwo = userSecurityQuestions.get(AkuraConstant.PARAM_INDEX_ONE);
        userQuestionOne.setAnswer(AkuraConstant.EMPTY_STRING);
        userQuestionTwo.setAnswer(AkuraConstant.EMPTY_STRING);
        submitAnswers.setUserQuestionOne(userQuestionOne);
        submitAnswers.setUserQuestionTwo(userQuestionTwo);
        modMap.addAttribute(SUBMIT_ANSWERS, submitAnswers);
        session.setAttribute(FROM_FORGOT_PASSWORD, FROM_FORGOT_PASSWORD);
        return REDIRECT_ANSWER_SECURITY_QUESTIONS_HTM;

    } else {

        userLogin.setUsername(null);
        bindingResult.addError(new ObjectError(ERROR, error));
        modMap.addAttribute(MESSAGE, null);
        modMap.addAttribute(MAIL_ERRORS, mailError);

        return FROM_FORGOT_PASSWORD;
    }

}

From source file:com.exxonmobile.ace.hybris.storefront.controllers.pages.checkout.SingleStepCheckoutController.java

@RequestMapping(value = "/placeOrder")
@RequireHardLogIn/*from  w w w.j  a  v a 2  s  .co  m*/
public String placeOrder(final Model model, @Valid final PlaceOrderForm placeOrderForm,
        final BindingResult bindingResult)
        throws CMSItemNotFoundException, InvalidCartException, ParseException {
    // validate the cart
    final CartData cartData = getCheckoutFlowFacade().getCheckoutCart();
    final boolean isAccountPaymentType = CheckoutPaymentType.ACCOUNT.getCode()
            .equals(cartData.getPaymentType().getCode());
    final String securityCode = placeOrderForm.getSecurityCode();
    final boolean termsChecked = placeOrderForm.isTermsCheck();

    if (!termsChecked) {
        GlobalMessages.addErrorMessage(model, "checkout.error.terms.not.accepted");
    }

    if (validateOrderform(placeOrderForm, model, cartData)) {
        placeOrderForm.setTermsCheck(false);
        model.addAttribute(placeOrderForm);
        return checkoutSummary(model);
    }

    if (!isAccountPaymentType && !getCheckoutFlowFacade().authorizePayment(securityCode)) {
        return checkoutSummary(model);
    }

    // validate quote negotiation
    if (placeOrderForm.isNegotiateQuote()) {
        if (StringUtils.isBlank(placeOrderForm.getQuoteRequestDescription())) {
            GlobalMessages.addErrorMessage(model, "checkout.error.noQuoteDescription");
            return checkoutSummary(model);
        } else {
            getCheckoutFlowFacade().setQuoteRequestDescription(
                    XSSFilterUtil.filter(placeOrderForm.getQuoteRequestDescription()));
        }
    }

    if (!termsChecked) {
        return checkoutSummary(model);
    }

    // validate replenishment
    if (placeOrderForm.isReplenishmentOrder()) {
        if (placeOrderForm.getReplenishmentStartDate() == null) {
            bindingResult.addError(
                    new FieldError(placeOrderForm.getClass().getSimpleName(), "replenishmentStartDate", ""));
            GlobalMessages.addErrorMessage(model, "checkout.error.replenishment.noStartDate");
            return checkoutSummary(model);
        }
        if (B2BReplenishmentRecurrenceEnum.WEEKLY.equals(placeOrderForm.getReplenishmentRecurrence())) {
            if (CollectionUtils.isEmpty(placeOrderForm.getnDaysOfWeek())) {
                GlobalMessages.addErrorMessage(model, "checkout.error.replenishment.no.Frequency");
                return checkoutSummary(model);
            }
        }
        final TriggerData triggerData = new TriggerData();
        populateTriggerDataFromPlaceOrderForm(placeOrderForm, triggerData);
        final ScheduledCartData scheduledCartData = getCheckoutFlowFacade().scheduleOrder(triggerData);
        return REDIRECT_PREFIX + "/checkout/replenishmentConfirmation/" + scheduledCartData.getJobCode();
    }

    final OrderData orderData;
    try {
        orderData = getCheckoutFlowFacade().placeOrder();
    } catch (final Exception e) {
        GlobalMessages.addErrorMessage(model, "checkout.placeOrder.failed");
        placeOrderForm.setNegotiateQuote(true);
        model.addAttribute(placeOrderForm);
        return checkoutSummary(model);
    }

    if (placeOrderForm.isNegotiateQuote()) {
        return REDIRECT_PREFIX + "/checkout/quoteOrderConfirmation/" + orderData.getCode();
    } else {
        return REDIRECT_PREFIX + "/checkout/orderConfirmation/" + orderData.getCode();

    }
}

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 w ww .j a v  a 2  s  . c om*/
    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";
}