Example usage for org.springframework.validation BindingResult reject

List of usage examples for org.springframework.validation BindingResult reject

Introduction

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

Prototype

void reject(String errorCode);

Source Link

Document

Register a global error for the entire target object, using the given error description.

Usage

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

@RequestMapping(value = { "edit/{eventId}/groupdraws/{round}" }, method = POST)
public ModelAndView postGroupDrawsForRound(@PathVariable Long eventId, @PathVariable Integer round,
        @ModelAttribute("Model") @Valid EventGroups eventGroups, BindingResult bindingResult,
        HttpServletRequest request) {//from ww  w. ja va 2  s.com
    Event event = eventDAO.findByIdFetchWithParticipantsAndGames(eventId);
    Iterator<Map.Entry<Integer, Set<Participant>>> iterator = eventGroups.getGroupParticipants().entrySet()
            .iterator();
    while (iterator.hasNext()) {
        Map.Entry<Integer, Set<Participant>> entry = iterator.next();
        if (entry.getValue() == null) {
            bindingResult.reject("PleaseSelectParticipantsForEachGroup");
        }
    }

    if (bindingResult.hasErrors()) {
        return getGroupDrawsView(event, eventGroups, round);
    }

    //remove games of players who no longer participate
    gameUtil.removeObsoleteGames(event);

    //remove games with teams that are no longer part of a group in the current round
    Iterator<Game> gameIterator = event.getGames().iterator();
    while (gameIterator.hasNext()) {
        Game game = gameIterator.next();
        Integer groupNumber = game.getGroupNumber();
        if (groupNumber != null && game.getRound().equals(round)) {
            Set<Participant> groupParticipants = eventGroups.getGroupParticipants().get(groupNumber);
            if (!groupParticipants.containsAll(game.getParticipants())) {
                gameIterator.remove();
                gameDAO.deleteById(game.getId());
            }
        }
    }

    //create missing games
    for (int groupNumber = 0; groupNumber < event.getNumberOfGroupsSecondRound(); groupNumber++) {
        Set<Participant> groupParticipants = eventGroups.getGroupParticipants().get(groupNumber);
        gameUtil.createMissingGames(event, groupParticipants, groupNumber, round);
    }

    return new ModelAndView("redirect:/events/event/" + eventId + "/groupgames/" + round);
}

From source file:easycare.web.password.ChangePasswordController.java

protected ModelAndView changePassword(HttpServletRequest request, HttpSession session,
        ChangePasswordForm changePasswordForm, BindingResult result, String view) {
    User user = this.sessionSecurityService.getCurrentUser();

    boolean validPassword = true;
    if (!result.hasErrors()) {
        // Check Password history
        if (userService.hasUsedPassword(user, changePasswordForm.getPassword())) {
            result.rejectValue("password", "password.change.history.error");
            validPassword = false;//from   w w  w  .j av a  2 s.  com
            userPasswordService.fireChangePasswordFailAlreadyUsedEvent(changePasswordForm.getUsername());
        }
    }

    if (result.hasErrors() || !validPassword) {
        // If password is in error, add the message code to be displayed
        ModelAndView mav = new ModelAndView(view);
        mav.addObject("changePasswordBean", changePasswordForm);
        if (!validPassword) {
            result.reject("password.change.fail");
        } else {
            userPasswordService.fireChangePasswordFailValidationEvent(changePasswordForm.getUsername(), result);
        }
        return mav;
    }

    // Update password token
    if (!updatePasswordToken(session)) {
        return new ModelAndView(INVALID_TOKEN_VIEW);
    }

    // Update user password
    user = userService.changePassword(user, changePasswordForm.getPassword());
    userPasswordService.fireChangePasswordSuccessfulEvent(changePasswordForm.getUsername());

    if (BooleanUtils.isTrue((Boolean) session.getAttribute(LOGOUT_AFTER_PASSWORD_CHANGE_KEY))) {
        return forceRelogin(request, user);
    }

    // Redirect to License Agreement page if needed
    if (!user.isLicenseAgreementAccepted()) {
        return new ModelAndView(new RedirectView("/licenseAgreement", true));
    }
    // Refresh User authorities
    sessionSecurityService.refreshUserContext(request, user, null);
    // Redirect to Home page
    return new ModelAndView(new RedirectView("/", true));
}

From source file:easycare.web.user.UserController.java

private boolean isProvidedDataValidToProceedUserCreation(final NewUserForm newUserForm,
        final BindingResult result) {
    boolean interpretingPhysicianFieldsValid = areMandatoryFieldsPresentForInterpretingPhysician(newUserForm,
            result);/* w ww  .j a  v  a  2 s  . co m*/
    if (!isPasswordValid(newUserForm, result) || result.hasErrors()) {
        if (!interpretingPhysicianFieldsValid) {
            result.reject(NEW_USER_CREATION_INTERPRETING_PHYSICIAN_FAILURE_MESSAGE);
        } else {
            result.reject(NEW_USER_CREATION_FAILURE_MESSAGE);
        }
        fireCreateUserFailedValidationEvent(newUserForm, result);
        return false;
    }

    return isUserValidForCreation(newUserForm, result);
}

From source file:org.egov.pgr.web.controller.complaint.citizen.CitizenComplaintRegistrationController.java

@RequestMapping(value = "anonymous/register", method = POST)
public String registerComplaintAnonymous(@Valid @ModelAttribute Complaint complaint, BindingResult resultBinder,
        RedirectAttributes redirectAttributes, HttpServletRequest request,
        @RequestParam("files") MultipartFile[] files, Model model) {

    if (!captchaUtils.captchaIsValid(request))
        resultBinder.reject("captcha.not.valid");

    if (isBlank(complaint.getComplainant().getEmail()) && isBlank(complaint.getComplainant().getMobile()))
        resultBinder.rejectValue("complainant.email", "email.or.mobile.ismandatory");

    if (isBlank(complaint.getComplainant().getName()))
        resultBinder.rejectValue("complainant.name", "complainant.name.ismandatory");

    if (complaint.getCrossHierarchyId() != null) {
        CrossHierarchy crosshierarchy = crossHierarchyService.findById(complaint.getCrossHierarchyId());
        complaint.setLocation(crosshierarchy.getParent());
        complaint.setChildLocation(crosshierarchy.getChild());
    }//from  w  ww  .j  a  va 2  s.c  om

    if (complaint.getLocation() == null && (complaint.getLat() == 0 || complaint.getLng() == 0))
        resultBinder.rejectValue(LOCATION, "location.required");

    if (resultBinder.hasErrors()) {
        if (null != complaint.getCrossHierarchyId())
            model.addAttribute("crossHierarchyLocation",
                    complaint.getChildLocation().getName() + " - " + complaint.getLocation().getName());
        return ANONYMOUS_COMPLAINT_REGISTRATION_FORM;
    }

    try {
        complaint.setSupportDocs(fileStoreUtils.addToFileStore(files, MODULE_NAME, true));
        complaintService.createComplaint(complaint);
    } catch (ValidationException e) {
        resultBinder.rejectValue(LOCATION, e.getMessage());
        return ANONYMOUS_COMPLAINT_REGISTRATION_FORM;
    }
    redirectAttributes.addFlashAttribute("complaint", complaint);
    return "redirect:/complaint/reg-success/" + complaint.getCrn();

}

From source file:org.egov.stms.web.controller.utils.SewerageApplicationValidator.java

public void validateNewApplicationUpdate(final SewerageApplicationDetails sewerageApplicationDetails,
        final BindingResult errors, final String workFlowAction) {
    if ((sewerageApplicationDetails.getStatus().getCode().equalsIgnoreCase(APPLICATION_STATUS_INITIALAPPROVED)
            || sewerageApplicationDetails.getStatus().getCode()
                    .equalsIgnoreCase(APPLICATION_STATUS_INSPECTIONFEEPAID))
            && "Reject".equalsIgnoreCase(workFlowAction)
            && StringUtils.isBlank(sewerageApplicationDetails.getApprovalComent()))
        errors.reject(REJECTION_COMMENTS_REQUIRED);

    if ((APPLICATION_STATUS_REJECTED.equalsIgnoreCase(sewerageApplicationDetails.getStatus().getCode())
            || APPLICATION_STATUS_FEEPAID.equalsIgnoreCase(sewerageApplicationDetails.getStatus().getCode())
            || APPLICATION_STATUS_ESTIMATENOTICEGEN
                    .equalsIgnoreCase(sewerageApplicationDetails.getStatus().getCode()))
            && workFlowAction.equalsIgnoreCase("Cancel")
            && StringUtils.isBlank(sewerageApplicationDetails.getApprovalComent()))
        errors.reject("err.application.cancel.comments.required");

    if (sewerageApplicationDetails.getConnectionDetail().getPropertyType() == null)
        errors.reject(NOTEMPTY_SEWERAGE_PROPERTYTYPE);
    else/*  w ww .jav a 2  s  . c  o  m*/
        validateNumberOfClosets(errors, sewerageApplicationDetails);

    if (sewerageApplicationDetails.getConnectionDetail() != null
            && sewerageApplicationDetails.getConnectionDetail().getPropertyType() != null)
        validateDonationAmount(sewerageApplicationDetails, errors);

    validateFieldInspectionDetails(sewerageApplicationDetails, errors);
    validateEstimationDetails(sewerageApplicationDetails, errors);

}

From source file:org.egov.wtms.application.service.ConnectionDemandService.java

public BindingResult getWaterTaxDue(WaterConnectionDetails waterConnectionDetails, BindingResult resultBinder) {
    if (isBlank(waterConnectionDetails.getEstimationNumber()))
        resultBinder.reject("err.demandnote.not.present");
    else {/*from   w  w w.  j  av a  2 s .  c  o  m*/
        BigDecimal waterChargesDue = waterConnectionDetailsService.getTotalAmount(waterConnectionDetails);
        if (waterChargesDue.signum() > 0)
            resultBinder.reject("err.water.charges.due", new Double[] { waterChargesDue.doubleValue() }, null);
    }
    return resultBinder;
}

From source file:org.encuestame.mvc.page.TweetPollController.java

/**
 * reCAPTCHA validate process.//w ww.java 2s .c  o  m
 * @param req {@link HttpServletRequest}.
 * @param challenge recaptcha_challenge_field parameter
 * @param response recaptcha_response_field paremeter
 * @param code code vote
 * @param result {@link BindingResult}.
 * @param model {@link ModelMap}.
 * @return view to redirect.
 * @throws UnknownHostException
 */
@RequestMapping(value = "/tweetpoll/vote/process", method = RequestMethod.POST)
public String processSubmit(HttpServletRequest req, @RequestParam("recaptcha_challenge_field") String challenge,
        @RequestParam("recaptcha_response_field") String response, @RequestParam("vote_code") String code,
        @ModelAttribute("captchaForm") UtilVoteCaptcha vote, BindingResult result, ModelMap model)
        throws UnknownHostException {
    setCss(model, "tweetpoll");
    log.info("recaptcha_challenge_field " + challenge);
    log.info("recaptcha_rforgotesponse_field " + response);
    log.info("code " + code.toString());
    log.info("vote " + vote.toString());
    log.info("model " + model.toString());
    challenge = filterValue(challenge);
    response = filterValue(response);
    code = filterValue(code);
    vote = (UtilVoteCaptcha) model.get("captchaForm");
    log.info("vote2--> " + vote.toString());
    final String IP = getIpClient(req);
    //security service
    final SecurityOperations securityService = getServiceManager().getApplicationServices()
            .getSecurityService();
    //check if captcha is valid
    final ReCaptchaResponse reCaptchaResponse = getReCaptcha().checkAnswer(req.getRemoteAddr(), challenge,
            response);
    //validation layer
    final ValidateOperations validation = new ValidateOperations(securityService);
    validation.validateCaptcha(reCaptchaResponse, result);
    log.info("reCaptchaResponse " + reCaptchaResponse.getErrorMessage());
    log.info("reCaptchaResponse " + reCaptchaResponse.isValid());
    log.info("result.hasErrors() " + result.hasErrors());
    if (result.hasErrors()) {
        //build new reCAPTCHA
        final String errMsg = reCaptchaResponse.getErrorMessage();
        final String html = getReCaptcha().createRecaptchaHtml(errMsg, null);
        vote.setCaptcha(html);
        vote.setCodeVote(code);
        model.addAttribute("captchaForm", vote);
        result.reject("form.problems");
        //reload page.
        return "voteCaptcha";
    } else {
        //Find Answer To Vote.
        final TweetPollSwitch tweetPoll = getTweetPollService().getTweetPollDao()
                .retrieveTweetsPollSwitch(code);
        model.addAttribute("switch", tweetPoll);
        //Validate Code.
        if (tweetPoll == null || !tweetPoll.getTweetPoll().getPublishTweetPoll()) {
            log.debug("tweetpoll answer not found");
            return "badTweetVote";
            //model.addAttribute("message", "Tweet Not Valid.");
        } else {
            // Vote
            try {
                getTweetPollService().validateIpVote(IP, tweetPoll.getTweetPoll());
                getTweetPollService().tweetPollVote(tweetPoll, IP, Calendar.getInstance().getTime());
                return "tweetVoted";

            } catch (Exception e) {
                log.error("Bad tweetpoll process submit --- >" + e);
                return "repeatedTweetVote";
            }
        }
    }
}

From source file:org.openmrs.module.cohort.web.controller.AddCohortController.java

@RequestMapping(value = "module/cohort/addcohort.form", method = RequestMethod.POST)
public String onSubmit(WebRequest request, HttpSession httpSession, HttpServletRequest request1,
        @RequestParam(required = false, value = "name") String cohort_name,
        @RequestParam(required = false, value = "description") String description,
        @RequestParam(required = false, value = "startDate") String start_date,
        @RequestParam(required = false, value = "endDate") String end_date,
        @ModelAttribute("cohortmodule") CohortM cohortmodule, BindingResult errors, ModelMap model) {
    CohortType cohort1 = new CohortType();
    CohortProgram prg = new CohortProgram();
    Location loc = new Location();
    String cohort_program = request.getParameter("format1");
    String cohort_type_name = request.getParameter("format");
    String location = request.getParameter("location");
    CohortService departmentService = Context.getService(CohortService.class);
    if (!Context.isAuthenticated()) {
        errors.reject("Required");
    }/*from  w ww  . j a  va 2s  .c  o m*/
    this.validator.validate(cohortmodule, errors);
    System.out.println("Before BR");
    if (errors.hasErrors()) {
        System.out.println("BR has errors: " + errors.getErrorCount());
        System.out.println(errors.getAllErrors());
        return "/module/cohort/addcohort";
    } else {
        /*try {
        java.util.Date start = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ENGLISH).parse(start_date);
         java.util.Date end = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ENGLISH).parse(end_date);
         if (start.compareTo(end) < 0 || start.compareTo(end)==0) {*/
        //cohortmodule.setLocation(location);
        List<CohortProgram> list2 = departmentService.findCohortProgram(cohort_program);
        List<CohortType> cohorttype1 = departmentService.findCohortType(cohort_type_name);
        LocationService service = Context.getLocationService();
        List<Location> formats = service.getLocations(location);
        for (int j = 0; j < formats.size(); j++) {
            loc = formats.get(j);
        }
        for (int i = 0; i < cohorttype1.size(); i++) {
            cohort1 = cohorttype1.get(i);
        }
        for (int a = 0; a < list2.size(); a++) {
            prg = list2.get(a);
        }
        cohortmodule.setCohortProgram(prg);
        cohortmodule.setClocation(loc);
        cohortmodule.setCohortType(cohort1);
        departmentService.saveCohort(cohortmodule);
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "insertion success");
        model.addAttribute("locations", formats);
        model.addAttribute("formats", cohorttype1);
        model.addAttribute("formats1", list2);
        model.addAttribute("cohortmodule", cohortmodule);
        if ("Next".equalsIgnoreCase(request.getParameter("next"))) {
            departmentService.saveCohort(cohortmodule);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "insertion success");
            String redirectUrl = "/module/cohort/addcohortattributes.form?ca=" + cohortmodule.getCohortId();
            return "redirect:" + redirectUrl;
        }

    }
    //}
    /*catch (ParseException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }     
    }*/
    return null;
}

From source file:org.openmrs.module.cohort.web.controller.AddCohortProgramController.java

@RequestMapping(value = "/module/cohort/addcohortprogram.form", method = RequestMethod.POST)
public String onSearch(WebRequest request, HttpSession httpSession, ModelMap model,
        @RequestParam(required = false, value = "name") String cohort_name,
        @RequestParam(required = false, value = "description") String description,
        @ModelAttribute("cohortprogram") CohortProgram cp, BindingResult errors) {
    CohortService departmentService = Context.getService(CohortService.class);
    if (!Context.isAuthenticated()) {
        errors.reject("Required");
    }//w w  w  . j a  va  2 s. c o m
    this.validator.validate(cp, errors);
    System.out.println("Before BR");
    if (errors.hasErrors()) {
        System.out.println("BR has errors: " + errors.getErrorCount());
        System.out.println(errors.getAllErrors());
        return "/module/cohort/addcohortprogram";
    }
    if (cohort_name.length() > 20) {
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "name cannot be greater than 20");
    } else {
        departmentService.saveCohortProgram(cp);
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "insertion success");
    }
    return null;
}

From source file:org.openmrs.module.cohort.web.controller.AddCohortTypeController.java

@RequestMapping(value = "/module/cohort/addcohorttype.form", method = RequestMethod.POST)
public String onSearch(WebRequest request, HttpSession httpSession, ModelMap model,
        @RequestParam(required = false, value = "name") String cohort_name,
        @RequestParam(required = false, value = "description") String description,
        @ModelAttribute("cohorttype") CohortType cohorttype, BindingResult errors) {
    CohortService departmentService = Context.getService(CohortService.class);
    if (!Context.isAuthenticated()) {
        errors.reject("Required");
    }/*from   www.  ja  va 2  s  .c  om*/
    this.validator.validate(cohorttype, errors);
    System.out.println("Before BR");
    if (errors.hasErrors()) {
        System.out.println("BR has errors: " + errors.getErrorCount());
        System.out.println(errors.getAllErrors());
        return "/module/cohort/addcohorttype";
    }
    if (cohort_name.length() > 20) {
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "name cannot be greater than 20");
    } else {
        departmentService.saveCohort(cohorttype);
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "insertion success");
    }
    return null;
}