Example usage for org.springframework.validation FieldError FieldError

List of usage examples for org.springframework.validation FieldError FieldError

Introduction

In this page you can find the example usage for org.springframework.validation FieldError FieldError.

Prototype

public FieldError(String objectName, String field, String defaultMessage) 

Source Link

Document

Create a new FieldError instance.

Usage

From source file:com.assetmanager.controller.RegisterController.java

/**
 * Handle the create account form submission.
 *
 * @param register the register form bean
 * @param binding the binding result/*w w  w  . j av  a 2 s . c o m*/
 * @param request the HTTP servlet request
 * @return the path
 */
@RequestMapping(value = "/create", method = RequestMethod.POST)
public final String submit(@ModelAttribute(REGISTER) @Valid final Register register,
        final BindingResult binding, final HttpServletRequest request) {
    final Locale locale = localeResolver.resolveLocale(request);

    if (binding.hasErrors()) {
        return "create";
    }

    final UserAccount user = new UserAccount(register.getUsername());
    user.setDisplayName(register.getDisplayName());
    user.setEmail(register.getEmail());
    user.setPassword(passwordEncoder.encodePassword(register.getPassword(), user.getSalt()));

    try {
        userDetailsService.addUser(user, locale);
    } catch (DuplicateUserException e) {
        binding.addError(new FieldError(REGISTER, "username",
                messageSource.getMessage("create.error.username", null, locale)));
        return "create";
    }

    return "redirect:/register/success";
}

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./*from w w w.  ja  v a 2  s. co  m*/
 * 
 * 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.//ww 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.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  w w.j a v  a 2 s . c  o  m*/
    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: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
 */// w w w .jav a 2s  . com
@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:org.axonframework.examples.addressbook.web.ContactsController.java

/**
 * Checks if the entered data for a contact is valid and if the provided contact has not yet been taken.
 *
 * @param contact       Contact to validate
 * @param bindingResult BindingResult that can contain error and can be used to store additional errors
 * @return true if the contact has errors, false otherwise
 *//*from   w w w  .j  ava2s . c  o m*/
private boolean contactHasErrors(ContactEntry contact, BindingResult bindingResult) {
    if (bindingResult.hasErrors() || !contactNameRepository.vacantContactName(contact.getName())) {
        ObjectError error = new FieldError("contact", "name",
                "The provided name \'" + contact.getName() + "\' already exists");
        bindingResult.addError(error);
        return true;
    }
    return false;
}

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

private List<ScheduleItem> processScheduleCsv(Event event, MultipartFile scheduleCsv,
        BindingResult bindingResult) {/*  w  ww. j a  v  a  2s.c  om*/
    List<ScheduleItem> scheduleItems = new ArrayList<>();
    byte[] scheduleCsvData = null;

    try {
        scheduleCsvData = scheduleCsv.getBytes();
    } catch (IOException e) {
        LOGGER.error("Error processing Schedule CSV File.", e);
        bindingResult.addError(
                new FieldError("uploadScheduleForm", "scheduleFile", "Error processing Schedule CSV File."));
        return null;
    }

    if (scheduleCsvData != null && scheduleCsv.getSize() > 0) {

        final ByteArrayInputStream bais = new ByteArrayInputStream(scheduleCsvData);

        ICsvBeanReader beanReader = null;
        try {
            final Reader reader = new InputStreamReader(bais);
            beanReader = new CsvBeanReader(reader, CsvPreference.STANDARD_PREFERENCE);

            // the header elements are used to map the values to the bean (names must match)
            final String[] header = beanReader.getHeader(true);
            final CellProcessor[] processors = CsvScheduleItemBean.getImportProcessors();

            CsvScheduleItemBean scheduleItemBean;
            while ((scheduleItemBean = beanReader.read(CsvScheduleItemBean.class, header,
                    processors)) != null) {
                final ScheduleItem scheduleItem;

                if (scheduleItemBean.getId() != null) {
                    scheduleItem = businessService.getScheduleItem(scheduleItemBean.getId());
                    if (scheduleItem == null) {
                        LOGGER.error(String.format("Schedule Item with Id '%s' does not exist.",
                                scheduleItemBean.getId()));
                        bindingResult.addError(new FieldError("uploadScheduleForm", "scheduleFile",
                                String.format("Schedule Item with Id '%s' does not exist.",
                                        scheduleItemBean.getId())));
                        continue;
                    }
                } else {
                    scheduleItem = new ScheduleItem();
                }

                if (scheduleItemBean.getEventId() != null) {
                    if (event.getId().equals(scheduleItemBean.getEventId())) {
                        scheduleItem.setEvent(event);
                    } else {
                        throw new IllegalArgumentException("Event ID did not match.");
                    }
                } else {
                    scheduleItem.setEvent(event);
                }

                scheduleItem.setFromTime(scheduleItemBean.getFromTime());
                scheduleItem.setToTime(scheduleItemBean.getToTime());
                scheduleItem.setScheduleItemType(scheduleItemBean.getType());
                scheduleItem.setTitle(scheduleItemBean.getTitle());

                if (scheduleItemBean.getPresentationId() != null) {
                    final Presentation presentation = businessService
                            .getPresentation(scheduleItemBean.getPresentationId());
                    scheduleItem.setPresentation(presentation);
                } else {
                    scheduleItem.setPresentation(null);
                }

                if (scheduleItemBean.getRoomId() != null) {
                    final Room room = businessService.getRoom(scheduleItemBean.getRoomId());
                    scheduleItem.setRoom(room);
                } else {
                    scheduleItem.setRoom(null);
                }

                scheduleItems.add(scheduleItem);

            }
        } catch (IOException e) {
            LOGGER.error("Error processing CSV File.", e);
            bindingResult.addError(new FieldError("uploadScheduleForm", "scheduleFile",
                    "Error processing Schedule CSV File."));
            return null;
        } finally {
            if (beanReader != null) {
                try {
                    beanReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    return scheduleItems;
}

From source file:fragment.web.AbstractBaseControllerTest.java

@Test
public void testHandleAjaxFormValidationException() {
    FieldError error = new FieldError("tenant", "teannt", "Invalid Tenant");
    List<ObjectError> lstError = new ArrayList<ObjectError>();
    lstError.add(error);/*from  w  w w .ja v  a  2s  . c  o  m*/
    BindingResult result = EasyMock.createMock(BindingResult.class);
    EasyMock.expect(result.getAllErrors()).andReturn(lstError).anyTimes();
    EasyMock.replay(result);
    Errors errors = new BindException(result);

    MockHttpServletResponse response = new MockHttpServletResponse();
    ModelAndView mav = controller.handleAjaxFormValidationException(new AjaxFormValidationException(errors),
            new MockHttpServletRequest(), response);
    Assert.assertNotNull(mav.getModelMap());
    Assert.assertEquals(420, response.getStatus());
    // ModelAndViewAssert.assertViewName(mav, expectedName);
}

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

@Transactional
@RequestMapping(value = { CHANGE_PASSWORD_MAPPING }, method = RequestMethod.POST)
public ModelAndView changePassword(@PathVariable String username,
        @ModelAttribute(CHANGE_PASSWORD_FORM_KEY) @Valid ChangePasswordForm form, BindingResult result,
        Model model) throws Exception {

    DuracloudUser user = this.userService.loadDuracloudUserByUsername(username);

    // check for errors
    if (!result.hasErrors()) {
        log.info("changing user password for {}", username);
        Long id = user.getId();/*from   ww  w .  ja v  a 2 s  .  co  m*/
        try {
            this.userService.changePassword(id, form.getOldPassword(), false, form.getPassword());
            return new ModelAndView(formatUserRedirect(username));
        } catch (InvalidPasswordException e) {
            result.addError(
                    new FieldError(CHANGE_PASSWORD_FORM_KEY, "oldPassword", "The old password is not correct"));
        }
    }

    log.debug("password form has errors for {}: returning...", username);
    addUserToModel(user, model);

    UserProfileEditForm editForm = new UserProfileEditForm();

    editForm.setFirstName(user.getFirstName());
    editForm.setLastName(user.getLastName());
    editForm.setEmail(user.getEmail());
    editForm.setSecurityQuestion(user.getSecurityQuestion());
    editForm.setSecurityAnswer(user.getSecurityAnswer());
    model.addAttribute(USER_PROFILE_FORM_KEY, editForm);
    return new ModelAndView(USER_EDIT_VIEW, model.asMap());

}

From source file:com.fengduo.bee.commons.component.FormModelMethodArgumentResolver.java

/**
 * {@inheritDoc}//from ww  w . j  av  a  2 s  .c  o  m
 * <p>
 * Downcast {@link org.springframework.web.bind.WebDataBinder} to
 * {@link org.springframework.web.bind.ServletRequestDataBinder} before binding.
 * 
 * @throws Exception
 * @see org.springframework.web.servlet.mvc.method.annotation.ServletRequestDataBinderFactory
 */
protected void bindRequestParameters(ModelAndViewContainer mavContainer, WebDataBinderFactory binderFactory,
        WebDataBinder binder, NativeWebRequest request, MethodParameter parameter) throws Exception {

    // Map<String, Boolean> hasProcessedPrefixMap = new HashMap<String, Boolean>();
    //
    // Class<?> targetType = binder.getTarget().getClass();
    // WebDataBinder simpleBinder = binderFactory.createBinder(request, null, null);
    Collection target = (Collection) binder.getTarget();

    Class<?>[] paramTypes = parameter.getMethod().getParameterTypes();
    Method method = parameter.getMethod();
    Object[] args = new Object[paramTypes.length];
    Map<String, Object> argMap = new HashMap<String, Object>(args.length);
    MapBindingResult errors = new MapBindingResult(argMap, "");
    ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();

    for (int i = 0; i < paramTypes.length; i++) {
        Class<?> paramType = paramTypes[i];

        MethodParameter methodParam = new MethodParameter(method, i);
        methodParam.initParameterNameDiscovery(parameterNameDiscoverer);
        String paramName = methodParam.getParameterName();
        // ??
        if (BeanUtils.isSimpleProperty(paramType)) {
            SimpleTypeConverter converter = new SimpleTypeConverter();
            Object value;
            // ?
            if (paramType.isArray()) {
                value = request.getParameterValues(paramName);
            } else {
                value = request.getParameter(paramName);
            }
            try {
                args[i] = converter.convertIfNecessary(value, paramType, methodParam);
            } catch (TypeMismatchException e) {
                errors.addError(new FieldError(paramName, paramName, e.getMessage()));
            }
        } else {
            // ???POJO
            if (paramType.isArray()) {
                ObjectArrayDataBinder binders = new ObjectArrayDataBinder(paramType.getComponentType(),
                        paramName);
                target.addAll(ArrayUtils.arrayConvert(binders.bind(request)));
            }
        }
    }

    // if (Collection.class.isAssignableFrom(targetType)) {// bind collection or array
    //
    // Type type = parameter.getGenericParameterType();
    // Class<?> componentType = Object.class;
    //
    // Collection target = (Collection) binder.getTarget();
    //
    // List targetList = new ArrayList(target);
    //
    // if (type instanceof ParameterizedType) {
    // componentType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
    // }
    //
    // if (parameter.getParameterType().isArray()) {
    // componentType = parameter.getParameterType().getComponentType();
    // }
    //
    // for (Object key : servletRequest.getParameterMap().keySet()) {
    // String prefixName = getPrefixName((String) key);
    //
    // // ?prefix ??
    // if (hasProcessedPrefixMap.containsKey(prefixName)) {
    // continue;
    // } else {
    // hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
    // }
    //
    // if (isSimpleComponent(prefixName)) { // bind simple type
    // Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest, prefixName);
    // Matcher matcher = INDEX_PATTERN.matcher(prefixName);
    // if (!matcher.matches()) { // ? array=1&array=2
    // for (Object value : paramValues.values()) {
    // targetList.add(simpleBinder.convertIfNecessary(value, componentType));
    // }
    // } else { // ? array[0]=1&array[1]=2
    // int index = Integer.valueOf(matcher.group(1));
    //
    // if (targetList.size() <= index) {
    // growCollectionIfNecessary(targetList, index);
    // }
    // targetList.set(index, simpleBinder.convertIfNecessary(paramValues.values(), componentType));
    // }
    // } else { // ? votes[1].title=votes[1].title&votes[0].title=votes[0].title&votes[0].id=0&votes[1].id=1
    // Object component = null;
    // // ? ?????
    // Matcher matcher = INDEX_PATTERN.matcher(prefixName);
    // if (!matcher.matches()) {
    // throw new IllegalArgumentException("bind collection error, need integer index, key:" + key);
    // }
    // int index = Integer.valueOf(matcher.group(1));
    // if (targetList.size() <= index) {
    // growCollectionIfNecessary(targetList, index);
    // }
    // Iterator iterator = targetList.iterator();
    // for (int i = 0; i < index; i++) {
    // iterator.next();
    // }
    // component = iterator.next();
    //
    // if (component == null) {
    // component = BeanUtils.instantiate(componentType);
    // }
    //
    // WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
    // component = componentBinder.getTarget();
    //
    // if (component != null) {
    // ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(
    // servletRequest,
    // prefixName,
    // "");
    // componentBinder.bind(pvs);
    // validateIfApplicable(componentBinder, parameter);
    // if (componentBinder.getBindingResult().hasErrors()) {
    // if (isBindExceptionRequired(componentBinder, parameter)) {
    // throw new BindException(componentBinder.getBindingResult());
    // }
    // }
    // targetList.set(index, component);
    // }
    // }
    // target.clear();
    // target.addAll(targetList);
    // }
    // } else if (MapWapper.class.isAssignableFrom(targetType)) {
    //
    // Type type = parameter.getGenericParameterType();
    // Class<?> keyType = Object.class;
    // Class<?> valueType = Object.class;
    //
    // if (type instanceof ParameterizedType) {
    // keyType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
    // valueType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[1];
    // }
    //
    // MapWapper mapWapper = ((MapWapper) binder.getTarget());
    // Map target = mapWapper.getInnerMap();
    // if (target == null) {
    // target = new HashMap();
    // mapWapper.setInnerMap(target);
    // }
    //
    // for (Object key : servletRequest.getParameterMap().keySet()) {
    // String prefixName = getPrefixName((String) key);
    //
    // // ?prefix ??
    // if (hasProcessedPrefixMap.containsKey(prefixName)) {
    // continue;
    // } else {
    // hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
    // }
    //
    // Object keyValue = simpleBinder.convertIfNecessary(getMapKey(prefixName), keyType);
    //
    // if (isSimpleComponent(prefixName)) { // bind simple type
    // Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest, prefixName);
    //
    // for (Object value : paramValues.values()) {
    // target.put(keyValue, simpleBinder.convertIfNecessary(value, valueType));
    // }
    // } else {
    //
    // Object component = target.get(keyValue);
    // if (component == null) {
    // component = BeanUtils.instantiate(valueType);
    // }
    //
    // WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
    // component = componentBinder.getTarget();
    //
    // if (component != null) {
    // ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(
    // servletRequest,
    // prefixName,
    // "");
    // componentBinder.bind(pvs);
    //
    // validateComponent(componentBinder, parameter);
    //
    // target.put(keyValue, component);
    // }
    // }
    // }
    // } else {// bind model
    // ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder;
    // servletBinder.bind(servletRequest);
    // }
}