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, String defaultMessage);

Source Link

Document

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

Usage

From source file:org.mifos.ui.core.controller.ViewOfficeHierarchyController.java

@RequestMapping(method = RequestMethod.POST)
public String processFormSubmit(@RequestParam(value = CANCEL_PARAM, required = false) String cancel,
        @ModelAttribute("formBean") ViewOfficeHierarchyFormBean formBean, BindingResult result,
        SessionStatus status) {//from   ww w .ja  v  a2  s  .c o m
    String viewName = REDIRECT_TO_ADMIN_SCREEN;

    if (StringUtils.isNotBlank(cancel)) {
        viewName = REDIRECT_TO_ADMIN_SCREEN;
        status.setComplete();
    } else if (result.hasErrors()) {
        viewName = populateFormBeanForErrorView(formBean);
    } else {
        try {
            UpdateConfiguredOfficeLevelRequest updateRequest = new UpdateConfiguredOfficeLevelRequest(
                    formBean.isSubRegionalOffice(), formBean.isRegionalOffice(), formBean.isAreaOffice());
            adminServiceFacade.updateOfficeLevelHierarchies(updateRequest);
            status.setComplete();
        } catch (BusinessRuleException e) {
            result.reject(e.getMessageKey(), "The update to office levels was not successful.");
            viewName = populateFormBeanForErrorView(formBean);
        }
    }
    return viewName;
}

From source file:org.ojbc.web.portal.validators.FirearmSearchCommandValidator.java

public void validate(FirearmSearchCommand firearmSearchCommand, BindingResult errors) {

    FirearmSearchRequest advanceSearch = firearmSearchCommand.getAdvanceSearch();

    if (StringUtils.isBlank(advanceSearch.getFirearmCounty())
            && StringUtils.isBlank(advanceSearch.getFirearmType())
            && StringUtils.isBlank(advanceSearch.getFirearmMake())
            && StringUtils.isBlank(advanceSearch.getFirearmModel())
            && StringUtils.isBlank(advanceSearch.getFirearmRegistrationNumber())
            && StringUtils.isBlank(advanceSearch.getFirearmSerialNumber())) {
        errors.reject("missingRequiredInput",
                "Search must have either a county, firearm type, make, model, serial number or registration number, or some combination thereof");
    }//w  w  w . j  a  v a2s.  co  m

    if (advanceSearch.getSourceSystems() == null || advanceSearch.getSourceSystems().size() == 0) {
        errors.reject("missingRequiredInput", "No Source Systems to search are selected.");
    }
}

From source file:org.ojbc.web.portal.validators.IncidentSearchCommandValidator.java

public void validate(IncidentSearchCommand incidentSearchCommand, BindingResult errors) {
    IncidentSearchRequest advanceSearch = incidentSearchCommand.getAdvanceSearch();

    if (StringUtils.isBlank(advanceSearch.getIncidentCityTown())
            && StringUtils.isBlank(advanceSearch.getIncidentNumber())
            && StringUtils.isBlank(advanceSearch.getIncidentType())) {
        errors.reject("missingRequiredInput",
                "Search must have either a city/town, incident # or type, or some combination thereof");
    }/*from  w  ww .j a v  a  2  s.  com*/

    if (hasDateRange(incidentSearchCommand)) {
        DateTime start = advanceSearch.getIncidentDateRangeStart();
        DateTime end = advanceSearch.getIncidentDateRangeEnd();

        if (start != null && end != null && start.isAfter(end)) {
            //errors.rejectValue("advanceSearch.incidentDateRangeStart", "Incident end date must be greater than or equal to start date");
            errors.reject("missingRequiredInput",
                    "Incident end date must be greater than or equal to start date");
        }
    }

    if (advanceSearch.getSourceSystems() == null || advanceSearch.getSourceSystems().size() == 0) {
        errors.reject("missingRequiredInput", "No Source Systems to search are selected.");
    }
}

From source file:org.ojbc.web.portal.validators.PersonSearchCommandValidator.java

public void validate(PersonSearchCommand personSearchCommand, BindingResult errors) {
    if (hasAgeRange(personSearchCommand) && hasDOB(personSearchCommand)) {
        errors.rejectValue("ageRangeStart", "ageAndDOBAtSameTime",
                "Age and DOB cannot be entered at the same time");
    }/*from   w  w w. j a va 2s . com*/

    PersonSearchRequest advanceSearch = personSearchCommand.getAdvanceSearch();
    if (StringUtils.isNotBlank(advanceSearch.getPersonSocialSecurityNumber())
            && !advanceSearch.getPersonSocialSecurityNumber().matches("\\d{3}-\\d{2}-\\d{4}")) {
        errors.rejectValue("advanceSearch.personSocialSecurityNumber", "ssnFormat",
                "SSN must be 9 digits seperated by dashes, (i.e. 999-99-9999)");
    }

    if (StringUtils.isNotBlank(advanceSearch.getPersonSID())
            && !advanceSearch.getPersonSID().matches("[a-zA-Z]\\d+")) {
        errors.rejectValue("advanceSearch.personSID", "sidFormat",
                "SID must be a letter followed by digits , (i.e. A123456789)");
    }

    if (hasDOB(personSearchCommand)) {
        DateTime startDob = advanceSearch.getPersonDateOfBirthRangeStart();
        DateTime endDob = advanceSearch.getPersonDateOfBirthRangeEnd();
        if (startDob != null && endDob != null && startDob.isAfter(endDob)) {
            errors.rejectValue("advanceSearch.personDateOfBirthRangeStart", "endDobBeforeStart",
                    "To DOB range must be after From");
        }

    }

    if (hasAgeRange(personSearchCommand)) {
        Integer startAge = personSearchCommand.getAgeRangeStart();
        Integer endAge = personSearchCommand.getAgeRangeEnd();
        if (startAge != null && endAge != null && startAge > endAge) {
            errors.rejectValue("ageRangeStart", "endAgeBeforeStart", "End Age must be after Begin Age");
        }

    }
    if (StringUtils.isBlank(advanceSearch.getPersonSurName()) //
            && StringUtils.isBlank(advanceSearch.getPersonSocialSecurityNumber()) //
            && StringUtils.isBlank(advanceSearch.getPersonSID()) //
            && StringUtils.isBlank(advanceSearch.getPersonDriversLicenseNumber()) //
            && StringUtils.isBlank(advanceSearch.getPersonFBINumber())) {
        errors.reject("missingRequiredInput",
                "Search must have either a last name or an identifier (SSN, SID, DL, or FBI Number)");
    }

    if (advanceSearch.getSourceSystems() == null || advanceSearch.getSourceSystems().size() == 0) {
        errors.reject("missingRequiredInput", "No Source Systems to search are selected.");
    }
}

From source file:org.ojbc.web.portal.validators.VehicleSearchCommandValidator.java

public void validate(VehicleSearchCommand vehicleSearchCommand, BindingResult errors) {

    VehicleSearchRequest advanceSearch = vehicleSearchCommand.getAdvanceSearch();

    if (StringUtils.isBlank(advanceSearch.getVehicleColor())
            && StringUtils.isBlank(advanceSearch.getVehicleMake())
            && StringUtils.isBlank(advanceSearch.getVehicleModel())
            && StringUtils.isBlank(advanceSearch.getVehiclePlateNumber())
            && StringUtils.isBlank(advanceSearch.getVehicleVIN())) {
        errors.reject("missingRequiredInput",
                "Search must have either a make, model, color, plate number or VIN, or some combination thereof");
    }//from   w  w w.  j a v a 2  s  .  c  o  m

    if (hasYearRange(vehicleSearchCommand)) {
        Integer startYear = vehicleSearchCommand.getAdvanceSearch().getVehicleYearRangeStart();
        Integer endYear = vehicleSearchCommand.getAdvanceSearch().getVehicleYearRangeEnd();

        if (endYear != null && startYear == null) {
            errors.reject("missingRequiredInput",
                    "If end year is specified, start year must also be specified");
        }

        if (startYear != null && endYear != null && startYear > endYear) {
            errors.reject("missingRequiredInput", "End year must be greater than or equal to start year");
        }
    }

    if (advanceSearch.getSourceSystems() == null || advanceSearch.getSourceSystems().size() == 0) {
        errors.reject("missingRequiredInput", "No Source Systems to search are selected.");
    }
}

From source file:org.wise.portal.presentation.web.controllers.ContactWiseController.java

/**
 * If the user is not logged in, we will check that they answered the reCaptcha correctly.
 * This is called after ContactWISEValidator.validate()
 *///from   www  .  jav a2s .  com
protected void checkRecaptcha(HttpServletRequest request, BindingResult result) {
    //get the signed in user or null if not signed in
    User user = ControllerUtil.getSignedInUser();

    if (user == null) {
        /*
         * the user is not signed in so we will display a reCaptcha if the server
         * has been set up with reCaptcha
         */

        //get the public and private keys from the wise.properties
        String reCaptchaPublicKey = wiseProperties.getProperty("recaptcha_public_key");
        String reCaptchaPrivateKey = wiseProperties.getProperty("recaptcha_private_key");

        //check if the public key is valid in case the admin entered it wrong
        boolean reCaptchaKeyValid = WISEAuthenticationProcessingFilter.isReCaptchaKeyValid(reCaptchaPublicKey,
                reCaptchaPrivateKey);

        if (reCaptchaKeyValid) {

            // get the google reCaptcha response
            String gRecaptchaResponse = request.getParameter("g-recaptcha-response");

            //check if the response is valid
            boolean isResponseValid = WISEAuthenticationProcessingFilter
                    .checkReCaptchaResponse(reCaptchaPrivateKey, reCaptchaPublicKey, gRecaptchaResponse);

            if (!isResponseValid) {
                // the reCaptcha failed so we will display an error

                String reCaptchaError = "";

                if (i18nProperties != null) {
                    //get the invalid reCaptcha message
                    reCaptchaError = i18nProperties.getProperty("error.contactwise-recaptcha");
                }

                //if the error.contactwise-recaptcha key is not in the properties, the value will be null
                if (reCaptchaError == null) {
                    reCaptchaError = "";
                }

                //create the error so that the form is not submitted and the message is displayed
                result.reject("400", reCaptchaError);
            }
        }
    }
}

From source file:ru.org.linux.topic.AddTopicController.java

@RequestMapping(value = "/add.jsp", method = RequestMethod.POST)
@CSRFNoAuto//  ww w  . ja va 2 s .c o  m
public ModelAndView doAdd(HttpServletRequest request, @Valid @ModelAttribute("form") AddTopicRequest form,
        BindingResult errors, @ModelAttribute("ipBlockInfo") IPBlockInfo ipBlockInfo) throws Exception {
    Map<String, Object> params = new HashMap<String, Object>();

    Template tmpl = Template.getTemplate(request);
    HttpSession session = request.getSession();

    String image = processUploadImage(request);

    Group group = form.getGroup();

    prepareModel(form, params, tmpl.getCurrentUser());

    Section section = null;

    if (group != null) {
        section = sectionService.getSection(group.getSectionId());
    }

    User user;

    if (!tmpl.isSessionAuthorized()) {
        if (form.getNick() != null) {
            user = form.getNick();
        } else {
            user = userDao.getAnonymous();
        }

        if (form.getPassword() == null) {
            errors.rejectValue("password", null, "?? ?");
        }
    } else {
        user = tmpl.getCurrentUser();
    }

    user.checkBlocked(errors);

    IPBlockDao.checkBlockIP(ipBlockInfo, errors, user);

    if (group != null && !groupPermissionService.isTopicPostingAllowed(group, user)) {
        errors.reject(null,
                "??  ? ?   ? ");
    }

    String message = processMessage(form.getMsg(), form.getMode());

    if (user.isAnonymous()) {
        if (message.length() > MAX_MESSAGE_LENGTH_ANONYMOUS) {
            errors.rejectValue("msg", null, "  ?");
        }
    } else {
        if (message.length() > MAX_MESSAGE_LENGTH) {
            errors.rejectValue("msg", null, "  ?");
        }
    }

    Screenshot scrn = null;

    if (section != null && groupPermissionService.isImagePostingAllowed(section, tmpl.getCurrentUser())) {
        scrn = processUpload(session, image, errors);

        if (section.isImagepost() && scrn == null && !errors.hasErrors()) {
            errors.reject(null, " ??");
        }
    }

    Poll poll = null;

    if (section != null && section.isPollPostAllowed()) {
        poll = preparePollPreview(form);
    }

    Topic previewMsg = null;

    if (group != null) {
        previewMsg = new Topic(form, user, request.getRemoteAddr());

        Image imageObject = null;

        if (scrn != null) {
            imageObject = new Image(0, 0, "gallery/preview/" + scrn.getMainFile().getName(),
                    "gallery/preview/" + scrn.getIconFile().getName());
        }

        params.put("message", prepareService.prepareTopicPreview(previewMsg,
                tagService.parseSanitizeTags(form.getTags()), poll, request.isSecure(), message, imageObject));
    }

    if (!form.isPreviewMode() && !errors.hasErrors()) {
        CSRFProtectionService.checkCSRF(request, errors);
    }

    if (!form.isPreviewMode() && !errors.hasErrors() && !tmpl.isSessionAuthorized()
            || ipBlockInfo.isCaptchaRequired()) {
        captcha.checkCaptcha(request, errors);
    }

    if (!form.isPreviewMode() && !errors.hasErrors()) {
        dupeProtector.checkDuplication(request.getRemoteAddr(), false, errors);
    }

    if (!form.isPreviewMode() && !errors.hasErrors() && group != null && section != null) {
        session.removeAttribute("image");

        Set<User> userRefs = lorCodeService.getReplierFromMessage(message);

        int msgid = messageDao.addMessage(request, form, message, group, user, scrn, previewMsg, userRefs);

        searchQueueSender.updateMessageOnly(msgid);

        Random random = new Random();

        String messageUrl = "view-message.jsp?msgid=" + msgid;

        if (!section.isPremoderated()) {
            return new ModelAndView(new RedirectView(messageUrl + "&nocache=" + random.nextInt()));
        }

        params.put("moderated", section.isPremoderated());
        params.put("url", messageUrl);

        return new ModelAndView("add-done-moderated", params);
    } else {
        return new ModelAndView("add", params);
    }
}