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:org.duracloud.account.app.controller.UserController.java

@Transactional
@RequestMapping(value = { FORGOT_PASSWORD_MAPPING }, method = RequestMethod.POST)
public String forgotPassword(
        @ModelAttribute(FORGOT_PASSWORD_FORM_KEY) @Valid ForgotPasswordForm forgotPasswordForm,
        BindingResult result, Model model, HttpServletRequest request) throws Exception {

    model.addAttribute(FORGOT_PASSWORD_FORM_KEY, forgotPasswordForm);

    if (!result.hasErrors()) {

        try {/*from  w  ww. j a  v a 2 s  .  co m*/

            String username = forgotPasswordForm.getUsername();

            if (StringUtils.isEmpty(forgotPasswordForm.getSecurityQuestion())) {
                DuracloudUser user = this.userService.loadDuracloudUserByUsernameInternal(username);
                forgotPasswordForm.setSecurityQuestion(user.getSecurityQuestion());
            }

            if (StringUtils.isEmpty(forgotPasswordForm.getSecurityAnswer())) {
                return FORGOT_PASSWORD_VIEW;
            }

            this.userService.forgotPassword(username, forgotPasswordForm.getSecurityQuestion(),
                    forgotPasswordForm.getSecurityAnswer());
        } catch (DBNotFoundException e) {
            result.addError(
                    new FieldError(FORGOT_PASSWORD_FORM_KEY, "username", "The username does not exist"));
            return FORGOT_PASSWORD_VIEW;
        } catch (InvalidPasswordException e) {
            result.addError(new FieldError(FORGOT_PASSWORD_FORM_KEY, "securityQuestion",
                    "The security answer is not correct"));
            return FORGOT_PASSWORD_VIEW;
        } catch (UnsentEmailException ue) {
            result.addError(new ObjectError(FORGOT_PASSWORD_FORM_KEY,
                    "Unable to send email to the address associated with the username"));
            return FORGOT_PASSWORD_VIEW;
        }

        return FORGOT_PASSWORD_SUCCESS_VIEW;
    }

    return FORGOT_PASSWORD_VIEW;
}

From source file:org.duracloud.account.app.controller.UserController.java

@Transactional
@RequestMapping(value = { "/change-password/{redemptionCode}" }, method = RequestMethod.POST)
public String anonymousPasswordChange(@PathVariable String redemptionCode,
        @ModelAttribute(CHANGE_PASSWORD_FORM_KEY) @Valid AnonymousChangePasswordForm form, BindingResult result,
        Model model) throws Exception {

    UserInvitation invitation = checkRedemptionCode(redemptionCode, model);
    if (invitation == null) {
        return ANONYMOUS_CHANGE_PASSWORD_FAILURE_VIEW;
    }//from ww w.jav  a2  s. c  o m

    String username = invitation.getAdminUsername();
    DuracloudUser user = this.userService.loadDuracloudUserByUsernameInternal(username);

    // check for errors
    if (!result.hasErrors()) {
        log.info("changing user password for {}", username);
        Long id = user.getId();
        try {
            this.userService.changePasswordInternal(id, user.getPassword(), true, form.getPassword());

            this.userService.redeemPasswordChangeRequest(user.getId(), redemptionCode);
            model.addAttribute("adminUrl", amaEndpoint.getUrl());
            return "anonymous-change-password-success";

        } catch (InvalidPasswordException e) {
            result.addError(
                    new FieldError(CHANGE_PASSWORD_FORM_KEY, "oldPassword", "The old password is not correct"));
        }
    }

    return ANONYMOUS_CHANGE_PASSWORD_VIEW;

}

From source file:com.aestheticsw.jobkeywords.web.html.JobController.java

/**
 * The search page relies on an AJAX call to submit the form-parameters and redraw only a
 * portion of the HTML page./*  w  w  w  .  j ava 2  s.c  om*/
 * 
 * If a validation error occurs for an initial search then the Javascript must correctly handle
 * the case where a subsequent search corrects the validation error and draws the response.
 * Correcting a validation error requires the Javascript to redraw both the <form> and the
 * results <div> HTML.
 *
 * If the search page is in a clean state then the search results only require redrawing the
 * <div> that contains the results. When an initial validation error occurs, only the <div> that
 * contains the form must be redrawn. When an initial valication is subsequencly corrected then
 * both <div>s must be redrawn.
 */
@RequestMapping(value = "/search", method = RequestMethod.POST)
public ModelAndView getTermListForSearchParameters(@Valid SearchFormBean searchFormBean, BindingResult result,
        RedirectAttributes redirect, @RequestParam(required = false) boolean isAjaxRequest) {

    Map<String, Object> modelMap = new HashMap<>();
    modelMap.put("searchFormBean", searchFormBean);
    if (result.hasErrors()) {
        searchFormBean.setHadFormErrors(true);
        modelMap.put("formErrors", result.getAllErrors());

        // Return the whole HTML page and let the Javascript select which <div> tags it wants to render. 
        return new ModelAndView("keywords", modelMap);
    }

    Locale locale = Locale.US;
    if (StringUtils.isNoneEmpty(searchFormBean.getCountry())) {
        locale = SearchUtils.lookupLocaleByCountry(searchFormBean.getCountry());
    }
    SearchParameters params = new SearchParameters(
            new QueryKey(searchFormBean.getQuery(), locale, searchFormBean.getCity()),
            searchFormBean.getJobCount(), searchFormBean.getStart(), searchFormBean.getRadius(),
            searchFormBean.getSort());

    TermFrequencyList termFrequencyList;
    try {
        termFrequencyList = termExtractorService.extractTerms(params);
    } catch (IndeedQueryException e) {
        searchFormBean.setHadFormErrors(true);
        result.addError(new FieldError("searchFormBean", "query",
                "No results found, check query expression: " + params));
        modelMap.put("formErrors", result.getAllErrors());

        // Return the whole HTML page and let the Javascript select which <div> tags it wants to render. 
        return new ModelAndView("keywords", modelMap);
    }

    searchFormBean.setHadFormErrors(false);
    modelMap.put("results", termFrequencyList);
    if (isAjaxRequest) {
        // Return only the results fragment. 
        return new ModelAndView("keywords :: query-results", modelMap);
    }
    return new ModelAndView("keywords", modelMap);
}

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

/**
 * Add a new speaker.//  w  w  w.j av a  2 s  .c o m
 *
 * @param cfpSubmissionSpeaker
 * @param bindingResult
 * @param model
 * @param request
 * @param redirectAttributes
 * @return
 */
@RequestMapping(value = "/speaker", method = RequestMethod.POST)
public String addCfpSpeaker(
        @Valid @ModelAttribute("cfpSubmissionSpeaker") CfpSubmissionSpeakerForm cfpSubmissionSpeaker,
        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";
    }

    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/cfp-speaker";
    }

    final Event eventFromDb = businessService.getCurrentEvent();
    final User user = (User) userService.loadUserByUsername(securityFacade.getUsername());

    final MultipartFile picture = cfpSubmissionSpeaker.getPictureFile();

    final CfpSpeakerImage cfpSpeakerImage = processPicture(picture, bindingResult);

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

    final CfpSubmissionSpeaker cfpSubmissionSpeakerToSave = new CfpSubmissionSpeaker();

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

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

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

        cfpSubmissionSpeakerToSave.setAvailableEntireEvent(cfpSubmissionSpeaker.isAvailableEntireEvent());

        final SortedSet<ConferenceDay> conferenceDays = eventFromDb.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(cfpSubmissionSpeakerToSave);
            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);
        }
    }

    businessService.saveCfpSubmissionSpeaker(cfpSubmissionSpeakerToSave, cfpSubmissionSpeakerConferenceDays);

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

From source file:com.devnexus.ting.web.controller.RegisterController.java

@RequestMapping(value = "/s/registerPageTwo", method = RequestMethod.POST)
public String validateDetailsForm(HttpServletRequest request, Model model,
        @Valid RegistrationDetails registerForm, BindingResult result) {

    Event currentEvent = businessService.getCurrentEvent();
    EventSignup eventSignup = businessService.getEventSignup();
    PaymentMethod paymentMethod = PaymentMethod.PAYPAL;
    prepareHeader(currentEvent, model);/*  ww w . jav  a 2s .  c o  m*/
    model.addAttribute("signupRegisterView", new SignupRegisterView(eventSignup));
    model.addAttribute("registrationDetails", registerForm);
    registerForm.setFinalCost(getTotal(registerForm));
    registerForm.setEvent(currentEvent);

    if (result.hasErrors()) {
        return "register2";
    }

    for (int index = 0; index < registerForm.getOrderDetails().size(); index++) {
        TicketOrderDetail orderDetails = registerForm.getOrderDetails().get(index);

        TicketGroup ticketGroup = businessService.getTicketGroup(orderDetails.getTicketGroup());

        if (!com.google.common.base.Strings.isNullOrEmpty(orderDetails.getCouponCode())
                && ticketGroup.getCouponCodes() != null && ticketGroup.getCouponCodes().size() > 0) {
            if (!hasCode(ticketGroup.getCouponCodes(), orderDetails.getCouponCode())) {
                result.addError(new FieldError("registrationDetails", "orderDetails[" + index + "].couponCode",
                        "Invalid Coupon Code."));
            }
        }

        if (StringUtils.isEmpty(orderDetails.getFirstName())) {
            result.rejectValue("orderDetails[" + index + "].firstName", "firstName.isRequired",
                    "First Name is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getLastName())) {
            result.rejectValue("orderDetails[" + index + "].lastName", "lastName.isRequired",
                    "Last Name is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getEmailAddress())) {
            result.rejectValue("orderDetails[" + index + "].emailAddress", "emailAddress.isReq uired",
                    "Email Address is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getCity())) {
            result.rejectValue("orderDetails[" + index + "].city", "city.isRequired", "City is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getState())) {
            result.rejectValue("orderDetails[" + index + "].state", "state.isRequired", "State is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getCountry())) {
            result.rejectValue("orderDetails[" + index + "].country", "country.isRequired",
                    "Country is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getJobTitle())) {
            result.rejectValue("orderDetails[" + index + "].jobTitle", "jobTitle.isRequired",
                    "Job Title is required.");
        }

        if (StringUtils.isEmpty(orderDetails.getCompany())) {
            result.rejectValue("orderDetails[" + index + "].company", "company.isRequired",
                    "Company is required.");
        }

    }

    if (result.hasErrors()) {

        return "register2";
    }

    for (TicketOrderDetail detail : registerForm.getOrderDetails()) {
        detail.setRegistration(registerForm);
    }

    switch (paymentMethod) {

    case INVOICE:
        registerForm.setPaymentState(RegistrationDetails.PaymentState.REQUIRES_INVOICE);
        registerForm.setFinalCost(getTotal(registerForm));
        businessService.createPendingRegistrationForm(registerForm);
        return "index";
    case PAYPAL:
        registerForm.setPaymentState(RegistrationDetails.PaymentState.PAYPAL_CREATED);
        registerForm.setFinalCost(getTotal(registerForm));
        registerForm = businessService.createPendingRegistrationForm(registerForm);
        String baseUrl = String.format("%s://%s:%d/", request.getScheme(), request.getServerName(),
                request.getServerPort());
        Payment createdPayment = runPayPal(registerForm, baseUrl);
        return "redirect:" + createdPayment.getLinks().stream().filter(link -> {
            return link.getRel().equals("approval_url");
        }).findFirst().get().getHref();
    default:
        throw new IllegalStateException("The system did not understand the payment type.");

    }

}

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

/**
 * Request handler for submit password.//from  ww  w .j  a v  a 2s.  c  o  m
 * 
 * @param submitPassword The model object that bind all passwords.
 * @param bindingResult The object to bind errors.
 * @param modelMap The model map binder.
 * @param session Get the currently logged in user.
 * @param request - an instance of request scope.
 * @return The view name of the submit password page.
 * @throws AkuraAppException Throws when fails.
 */
@RequestMapping(value = SUBMIT_PASSWORD, method = RequestMethod.POST)
public String submitPassword(@ModelAttribute(SUBMITPASSWORD) WrapperChangePassword submitPassword,
        BindingResult bindingResult, ModelMap modelMap, HttpSession session, HttpServletRequest request)
        throws AkuraAppException {

    String mailError = null;

    String userName = (String) session.getAttribute(USER_NAME);
    UserLogin userLogin = (UserLogin) session.getAttribute(USERLOGIN);
    UserInfo userInfo = (UserInfo) session.getAttribute(USER);

    if (userName == null && userLogin == null) {

        return FAILURE;

    } else if (session.getAttribute(USERLOGIN) != null) {

        userLogin = (UserLogin) session.getAttribute(USERLOGIN);

    } else {

        userLogin = userService.getAnyUser(userName);
    }

    userPasswordValidator.validate(submitPassword, bindingResult);

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

    String password = submitPassword.getOldPassword().trim();
    String newPassword = submitPassword.getNewPassword().trim();
    String confirmPassword = submitPassword.getConfirmPassword().trim();

    if (!userService.validatePassword(password, userLogin)) {
        bindingResult.addError(new ObjectError(AkuraWebConstant.USER_INCORRECT_OLD_PASSWORD,
                new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.USER_INCORRECT_OLD_PASSWORD)));

    } else if (!newPassword.equals(confirmPassword)) {

        bindingResult.addError(new ObjectError(AkuraWebConstant.INCORRECT_COMPARE_PASSWORD,
                new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.INCORRECT_COMPARE_PASSWORD)));
    }

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

    loginController.getPublications(modelMap, request);

    if (userService.changePassword(userLogin, newPassword)) {

        userLogin.setStatus(true);

        /* check user password status, whether system generated or not. */
        if (userLogin.getGeneratedPassword()) {
            userLogin.setGeneratedPassword(Boolean.FALSE);
        }
        userService.updateUser(userLogin);

        try {
            setMailProprties(userLogin, newPassword,
                    PropertyReader.getPropertyValue(EMAIL_PROPERTIES, CHANGE_PASSWORD_SUBJECT),
                    PropertyReader.getPropertyValue(EMAIL_PROPERTIES, NEW_PASSWORD_TO_USER));
        } catch (MailException e) {

            if (e instanceof MailAuthenticationException) {

                mailError = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.EMAIL_AUTHENTICATION_ERROR);
                LOG.error(AkuraWebConstant.EMAIL_AUTHENTICATION_ERROR, e);

            } else if (e.getCause() instanceof MailSendException) {
                mailError = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.EMAIL_SEND_ERROR);
                LOG.error(AkuraWebConstant.EMAIL_SEND_ERROR, e);
            }

            mailError = new ErrorMsgLoader().getErrorMessage(AkuraConstant.EMAIL_ERROR);
            LOG.error(AkuraConstant.EMAIL_ERROR, e);
        } catch (AkuraAppException e) {
            mailError = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.EMAIL_SEND_ERROR);
            LOG.error(AkuraWebConstant.EMAIL_SEND_ERROR, e);
        }

        if (mailError != null) {

            bindingResult.addError(new ObjectError(MAIL_ERRORS, mailError));

            return userInfo.getDefaultUserHomeUrl();

        }

    }
    return userInfo.getDefaultUserHomeUrl();
}

From source file:com.virtusa.akura.reporting.controller.CustomStaffReportController.java

/**
 * Generate School Teacher List Report and School Section Head List Report request processing method.
 *
 * @param schoolStaffHeadList a model to bind values.
 * @param errors To bind errors.//ww w  .j a  v a2s . c o  m
 * @param response the servlet response.
 * @return The view name of the request handler.
 * @throws AkuraAppException throw exception if request processing fails.
 */
@RequestMapping(value = LIST_REPORTS, method = RequestMethod.POST)
public String showTeacherListReport(
        @ModelAttribute(SCHOOL_TEACHER_AND_SECTION_HEAD_LIST) SchoolTeacherAndSectionHeadList schoolStaffHeadList,
        BindingResult errors, HttpServletResponse response) throws AkuraAppException {

    LOG.info(SCHOOL_TEACHER_LIST_LOG);

    JRBeanCollectionDataSource datasource;

    schoolTeacherListSectionHeadListValidator.validate(schoolStaffHeadList, errors);

    if (errors.hasErrors()) {

        return REPORTING_SCHOOL_TEACHER_LIST_AND_SECTION_HEAD_LIST;

    }

    Map<String, Object> parameterMap = new HashMap<String, Object>();

    // if the list type is true then generate the Teacher List Report.
    if (schoolStaffHeadList.getListType() == AkuraConstant.PARAM_INDEX_ONE) {

        List<Staff> staffByCategoryList = null;
        if (schoolStaffHeadList.getCatogaryID() == -1) {
            staffByCategoryList = staffService.getAllAvailableStaffWithOutDeparture();

            parameterMap.put(STAFF_CATEGORY_TYPE, ALL);

        } else {
            staffByCategoryList = staffService.getStaffListByCategory(schoolStaffHeadList.getCatogaryID());

            parameterMap.put(STAFF_CATEGORY_TYPE,
                    staffCommonService.getStaffCategory(schoolStaffHeadList.getCatogaryID()).getDescription());

        }

        if (staffByCategoryList.isEmpty()) {

            errors.addError(new FieldError(SCHOOL_TEACHER_AND_SECTION_HEAD_LIST, LIST_TYPE,
                    MEMBERS_ARE_NOT_ASSIGNED_ERROR_CATEGORY));
            return REPORTING_SCHOOL_TEACHER_LIST_AND_SECTION_HEAD_LIST;
        }

        // Sort the staff List and Set to data source.
        datasource = new JRBeanCollectionDataSource(SortUtil.sortStaffList(staffByCategoryList));
        parameterMap.put(TITLE, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, STAFF_REPORT));
        parameterMap.put(YEAR, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, YEAR_STRING));
        parameterMap = populateParameterMap(parameterMap, datasource);

        ReportUtil.displayReportInPdfForm(response, datasource, parameterMap, STAFF_REPORTS);

    } else if (schoolStaffHeadList.getListType() == AkuraConstant.PARAM_INDEX_THREE) {

        List<ClassTeacher> classTeacherList = getClassTeacherListByGrade(schoolStaffHeadList.getGradeId());

        if (classTeacherList.isEmpty()) {

            errors.addError(new FieldError(SCHOOL_TEACHER_AND_SECTION_HEAD_LIST, LIST_TYPE,
                    TEACHERS_ARE_NOT_ASSIGNED_TO_THE_SELECTED_CLASS));
            return REPORTING_SCHOOL_TEACHER_LIST_AND_SECTION_HEAD_LIST;
        }
        datasource = new JRBeanCollectionDataSource(SortUtil.sortClassTeacherList(classTeacherList));

        parameterMap = populateParameterMap(parameterMap, datasource);
        parameterMap.put(CLASS_GRADE,
                PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, CLASS_GRADE_TITLE));
        parameterMap.put(TITLE, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, CLASS_TEACHERS));
        parameterMap.put(GRADE_LOW, schoolStaffHeadList.getGradeDescription());
        parameterMap.put(YEAR, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, YEAR_STRING));
        parameterMap.put(CLASS, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, CLASS_TITLE));

        ReportUtil.displayReportInPdfForm(response, datasource, parameterMap, CLASS_TEACHER_LIST);

    } else {

        List<SectionHead> sectionHeadList = getAllCurrrentSectionHeads(
                staffService.getCurrentSectionHeadList(new Date()));

        if (sectionHeadList.isEmpty()) {

            errors.addError(new FieldError(SCHOOL_TEACHER_AND_SECTION_HEAD_LIST, LIST_TYPE,
                    SECTIONAL_HEADS_ARE_NOT_ASSIGNED));
            return REPORTING_SCHOOL_TEACHER_LIST_AND_SECTION_HEAD_LIST;
        }

        datasource = new JRBeanCollectionDataSource(SortUtil.sortSectionHeadList(sectionHeadList));
        parameterMap.put(TITLE, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, SECTION_HEADS));
        parameterMap.put(START_DATE2, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, START_DATE));
        parameterMap.put(END_DATE2, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, END_DATE));
        parameterMap.put(SECTION2, PropertyReader.getPropertyValue(ReportUtil.REPORT_TEMPLATE, SECTION));

        parameterMap = populateParameterMap(parameterMap, datasource);

        ReportUtil.displayReportInPdfForm(response, datasource, parameterMap, SECTION_HEADS_REPORT);
    }

    return null;
}

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

@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("customer") User user, ModelMap model, BindingResult result,
        SessionStatus status) {//from  w w  w . j a  v  a 2s .  com

    singUpValidator.validate(user, result);

    Map<String, String> groupMap = null;

    try {

        if (result.hasErrors()) {

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

            return "signUp";
        }

        String userName = user.getFirstName().toLowerCase() + user.getLastName().toLowerCase();

        // For account creation, we should get an instance of Account from the DataStore,
        // set the account properties and create it in the proper directory.
        Account account = stormpath.getDataStore().instantiate(Account.class);
        account.setEmail(user.getEmail());
        account.setGivenName(user.getFirstName());
        account.setSurname(user.getLastName());
        account.setPassword(user.getPassword());
        account.setUsername(userName);

        // Saving the account to the Directory where the Tooter application belongs.
        Directory directory = stormpath.getDirectory();
        directory.createAccount(account);

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

        user.setUserName(userName);
        customerDao.saveCustomer(user);

        status.setComplete();

    } catch (RuntimeException re) {

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

        result.addError(new ObjectError("password", re.getMessage()));
        re.printStackTrace();
        return "signUp";

    } catch (Exception e) {
        e.printStackTrace();
    }

    //form success
    return "redirect:/login/message?loginMsg=registered";
}

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

@RequestMapping(value = "/cfp", method = RequestMethod.POST)
public String addCfp(@Valid @ModelAttribute("cfpSubmission") CfpSubmissionForm cfpSubmission,
        BindingResult bindingResult, ModelMap model, HttpServletRequest request,
        RedirectAttributes redirectAttributes) {

    if (request.getParameter("cancel") != null) {
        return "redirect:/s/index";
    }//from w ww.jav  a2s  . com
    if (request.getParameter("addSpeaker") != null) {
        prepareReferenceData(model, request.isSecure());
        CfpSubmissionSpeaker speaker = new CfpSubmissionSpeaker();
        speaker.setCfpSubmission(cfpSubmission);
        cfpSubmission.getSpeakers().add(speaker);
        return "/cfp";
    }

    if (request.getParameter("removeSpeaker") != null) {
        prepareReferenceData(model, request.isSecure());
        cfpSubmission.getSpeakers().remove(Integer.valueOf(request.getParameter("removeSpeaker")).intValue());
        return "/cfp";
    }

    final String reCaptchaEnabled = environment.getProperty("recaptcha.enabled");
    final String recaptchaPrivateKey = environment.getProperty("recaptcha.privateKey");

    if (Boolean.valueOf(reCaptchaEnabled)) {
        String remoteAddr = request.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey(recaptchaPrivateKey);

        String challenge = request.getParameter("recaptcha_challenge_field");
        String uresponse = request.getParameter("recaptcha_response_field");
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

        if (!reCaptchaResponse.isValid()) {
            ObjectError error = new ObjectError("error", "Please insert the correct CAPTCHA.");
            bindingResult.addError(error);
            prepareReferenceData(model, request.isSecure());
            return "/cfp";
        }
    }

    if (bindingResult.hasErrors()) {
        prepareReferenceData(model, request.isSecure());
        return "/cfp";
    }

    final Event eventFromDb = businessService.getCurrentEvent();
    final CfpSubmission cfpSubmissionToSave = new CfpSubmission();

    if (cfpSubmission.getSpeakers().size() < 1) {
        ObjectError error = new ObjectError("error", "Please submit at least 1 speaker.");
        bindingResult.addError(error);
        prepareReferenceData(model, request.isSecure());
        return "/cfp";
    }

    if (cfpSubmission.getPictureFiles().size() != cfpSubmission.getSpeakers().size()) {
        ObjectError error = new ObjectError("error", "Please submit a picture for each speaker.");
        bindingResult.addError(error);
        prepareReferenceData(model, request.isSecure());
        return "/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());

    int index = 0;
    for (CfpSubmissionSpeaker cfpSubmissionSpeaker : cfpSubmission.getSpeakers()) {

        final MultipartFile picture = cfpSubmission.getPictureFiles().get(index);
        InputStream pictureInputStream = null;

        try {
            pictureInputStream = picture.getInputStream();
        } catch (IOException e) {
            LOGGER.error("Error processing Image.", e);
            bindingResult.addError(new FieldError("cfpSubmission", "pictureFile", "Error processing Image."));
            prepareReferenceData(model, request.isSecure());
            return "/cfp";
        }

        if (pictureInputStream != null && picture.getSize() > 0) {
            SystemInformationUtils
                    .setSpeakerImage(
                            "CFP_" + cfpSubmissionSpeaker.getFirstName() + "_"
                                    + cfpSubmissionSpeaker.getLastName() + "_" + picture.getOriginalFilename(),
                            pictureInputStream);
        }

        index++;

        final CfpSubmissionSpeaker cfpSubmissionSpeakerToSave = new CfpSubmissionSpeaker();

        cfpSubmissionSpeakerToSave.setEmail(cfpSubmissionSpeaker.getEmail());
        cfpSubmissionSpeakerToSave.setBio(cfpSubmissionSpeaker.getBio());
        cfpSubmissionSpeakerToSave.setFirstName(cfpSubmissionSpeaker.getFirstName());
        cfpSubmissionSpeakerToSave.setGithubId(cfpSubmissionSpeaker.getGithubId());
        cfpSubmissionSpeakerToSave.setGooglePlusId(cfpSubmissionSpeaker.getGooglePlusId());
        cfpSubmissionSpeakerToSave.setLanyrdId(cfpSubmissionSpeaker.getLanyrdId());
        cfpSubmissionSpeakerToSave.setLastName(cfpSubmissionSpeaker.getLastName());
        cfpSubmissionSpeakerToSave.setLinkedInId(cfpSubmissionSpeaker.getLinkedInId());
        cfpSubmissionSpeakerToSave.setTwitterId(cfpSubmissionSpeaker.getTwitterId());
        cfpSubmissionSpeakerToSave.setLocation(cfpSubmissionSpeaker.getLocation());
        cfpSubmissionSpeakerToSave.setMustReimburseTravelCost(cfpSubmissionSpeaker.isMustReimburseTravelCost());
        cfpSubmissionSpeakerToSave.setTshirtSize(cfpSubmissionSpeaker.getTshirtSize());
        cfpSubmissionSpeakerToSave.setPhone(cfpSubmissionSpeaker.getPhone());
        cfpSubmissionSpeakerToSave.setCfpSubmission(cfpSubmissionToSave);
        cfpSubmissionToSave.getSpeakers().add(cfpSubmissionSpeakerToSave);

    }

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

    return "redirect:/s/add-cfp-success";
}

From source file:org.duracloud.account.app.controller.AccountUsersController.java

@Transactional
@RequestMapping(value = ACCOUNT_USERS_MAPPING, method = RequestMethod.POST)
public ModelAndView sendInvitations(@PathVariable Long accountId,
        @ModelAttribute(INVITATION_FORM_KEY) @Valid InvitationForm invitationForm, BindingResult result,
        Model model, RedirectAttributes redirectAttributes) throws Exception {
    log.info("sending invitations from account {}", accountId);
    boolean hasErrors = result.hasErrors();
    AccountService service = getAccountService(accountId);

    if (!hasErrors) {

        List<String> emailAddresses = EmailAddressesParser.parse(invitationForm.getEmailAddresses());

        List<String> failedEmailAddresses = new ArrayList<String>();
        String adminUsername = getUser().getUsername();

        for (String emailAddress : emailAddresses) {
            try {
                UserInvitation ui = service.inviteUser(emailAddress, adminUsername,
                        notificationMgr.getEmailer());
                String template = "Successfully created user invitation on "
                        + "account {0} for {1} expiring on {2}";
                String message = MessageFormat.format(template, ui.getAccount().getId(), ui.getUserEmail(),
                        ui.getExpirationDate());
                log.info(message);/* w w  w.  j  a  v a  2 s.  c o  m*/
            } catch (UnsentEmailException e) {
                failedEmailAddresses.add(emailAddress);
            }
        }

        if (!failedEmailAddresses.isEmpty()) {
            String template = "Unable to send an email to the following recipients, "
                    + "but the user has been added: {0}";
            String message = MessageFormat.format(template, failedEmailAddresses);

            result.addError(new ObjectError("emailAddresses", message));
            hasErrors = true;
        }
    }

    if (hasErrors) {
        addUserToModel(model);
        get(service, model);
        return new ModelAndView(ACCOUNT_USERS_VIEW_ID);
    }

    setSuccessFeedback("Successfully sent invitations.", redirectAttributes);
    return createAccountRedirectModelAndView(accountId, ACCOUNT_USERS_PATH);
}