Example usage for org.springframework.validation BindingResult rejectValue

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

Introduction

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

Prototype

void rejectValue(@Nullable String field, String errorCode, String defaultMessage);

Source Link

Document

Register a field error for the specified field of the current object (respecting the current nested path, if any), using the given error description.

Usage

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");
    }/*w w  w  . j ava2 s . c  o m*/

    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.springframework.samples.petclinic.web.OwnerController.java

@RequestMapping(value = "/owners", method = RequestMethod.GET)
public String processFindForm(Owner owner, BindingResult result, Model model) {

    // allow parameterless GET request for /owners to return all records
    if (owner.getLastName() == null && owner.getCity() == null) {
        owner.setLastName(""); // empty string signifies broadest possible search
        owner.setCity(""); // empty string signifies broadest possible search
    }/*from w  ww  .jav  a2 s  . co  m*/

    // find owners by last name
    Collection<Owner> results;
    if (StringUtils.isNotEmpty(owner.getLastName())) {
        results = this.clinicService.findOwnerByLastName(owner.getLastName());
    } else if (StringUtils.isNotEmpty(owner.getCity())) {
        results = this.clinicService.findOwnerByCity(owner.getCity());
    } else {
        // find all
        results = this.clinicService.findOwnerByLastName("");
    }
    if (results.size() < 1) {
        // no owners found
        result.rejectValue("lastName", "notFound", "not found");
        return "owners/findOwners";
    }
    if (results.size() > 1) {
        // multiple owners found
        model.addAttribute("selections", results);
        return "owners/ownersList";
    } else {
        // 1 owner found
        owner = results.iterator().next();
        return "redirect:/owners/" + owner.getId();
    }
}

From source file:org.wise.portal.presentation.web.controllers.teacher.run.CreateRunController.java

/**
 * Third page handler. This is where user selects postLevel and real time settings
 *///w  ww . ja  v  a  2 s  . c  o m
@RequestMapping(params = "_page=3")
public String processThirdPage(final @ModelAttribute("runParameters") RunParameters runParameters,
        final BindingResult result, final ModelMap modelMap, final HttpServletRequest request) {
    modelMap.put("periodNames", DefaultPeriodNames.values());

    if (runParameters.getPeriodNames() == null || runParameters.getPeriodNames().size() == 0) {
        if (runParameters.getManuallyEnteredPeriods() == "") {
            result.rejectValue("periodNames", "setuprun.error.selectperiods",
                    "You must select one or more periods or manually" + " create your period names.");
        } else {
            // check if manually entered periods is an empty string or just "," If yes, throw error
            if (runParameters.getManuallyEnteredPeriods() == null
                    || StringUtils.trim(runParameters.getManuallyEnteredPeriods()).length() == 0
                    || StringUtils.trim(runParameters.getManuallyEnteredPeriods()).equals(",")) {
                result.rejectValue("periodNames", "setuprun.error.selectperiods",
                        "You must select one or more periods or manually" + " create your period names.");
            } else {
                String[] parsed = StringUtils.split(runParameters.getManuallyEnteredPeriods(), ",");
                if (parsed.length == 0) {
                    result.rejectValue("periodNames", "setuprun.error.whitespaceornonalphanumeric",
                            "Manually entered"
                                    + " periods cannot contain whitespace or non-alphanumeric characters.");
                    return "teacher/run/create/createrunperiods";
                }
                Set<String> parsedAndTrimmed = new TreeSet<String>();
                for (String current : parsed) {
                    String trimmed = StringUtils.trim(current);
                    if (trimmed.length() == 0 || StringUtils.contains(trimmed, " ")
                            || !StringUtils.isAlphanumeric(trimmed) || trimmed.equals(",")) {
                        result.rejectValue("periodNames", "setuprun.error.whitespaceornonalphanumeric",
                                "Manually entered"
                                        + " periods cannot contain whitespace or non-alphanumeric characters.");
                        break;
                    } else {
                        parsedAndTrimmed.add(trimmed);
                    }
                }
                runParameters.setPeriodNames(parsedAndTrimmed);
                runParameters.setManuallyEnteredPeriods("");
            }
        }
    } else if (runParameters.getManuallyEnteredPeriods() != "") {
        result.rejectValue("periodNames", "setuprun.error.notsupported",
                "Selecting both periods AND" + " manually entering periods is not supported.");
    }
    if (result.hasErrors()) {
        return "teacher/run/create/createrunperiods";
    }

    postLevelTextMap = new HashMap<Long, String>();
    String defaultPostLevelHighMessage = messageSource.getMessage(
            "presentation.web.controllers.teacher.run.CreateRunController.postLevelHighMessage", null,
            Locale.US);
    String postLevelHighMessage = messageSource.getMessage(
            "presentation.web.controllers.teacher.run.CreateRunController.postLevelHighMessage", null,
            defaultPostLevelHighMessage, request.getLocale());
    String defaultPostLevelLowMessage = messageSource.getMessage(
            "presentation.web.controllers.teacher.run.CreateRunController.postLevelLowMessage", null,
            Locale.US);
    String postLevelLowMessage = messageSource.getMessage(
            "presentation.web.controllers.teacher.run.CreateRunController.postLevelLowMessage", null,
            defaultPostLevelLowMessage, request.getLocale());

    postLevelTextMap.put(5l, postLevelHighMessage);
    postLevelTextMap.put(1l, postLevelLowMessage);

    Project project = runParameters.getProject();
    String maxWorkgroupSizeStr = wiseProperties.getProperty("maxWorkgroupSize", "3");
    int maxWorkgroupSize = Integer.parseInt(maxWorkgroupSizeStr);
    runParameters.setMaxWorkgroupSize(maxWorkgroupSize);
    modelMap.put("maxWorkgroupSize", maxWorkgroupSize);
    modelMap.put("implementedPostLevels", IMPLEMENTED_POST_LEVELS);
    modelMap.put("postLevelTextMap", postLevelTextMap);
    modelMap.put("minPostLevel", this.getMinPostLevel(project));
    runParameters.setEnableRealTime(true);
    return "teacher/run/create/createrunconfigure";
}

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

@RequestMapping(value = "/add.jsp", method = RequestMethod.POST)
@CSRFNoAuto//from  www  . j a v a 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);
    }
}

From source file:ubic.gemma.web.controller.common.description.bibref.PubMedQueryControllerImpl.java

@Override
@RequestMapping(method = RequestMethod.POST)
public ModelAndView onSubmit(HttpServletRequest request, PubMedSearchCommand command, BindingResult result,
        SessionStatus status) {// w ww. ja v a 2s. c om

    // in the future we can search in other ways.
    String accession = command.getAccession();

    if (StringUtils.isBlank(accession)) {

        result.rejectValue("search", "errors.pubmed.noaccession", "Accession was missing");
        return new ModelAndView("bibRefSearch");
    }

    // first see if we already have it in the system.
    BibliographicReference bibRefFound = bibliographicReferenceService.findByExternalId(accession);
    if (bibRefFound != null) {
        request.setAttribute("existsInSystem", Boolean.TRUE);
        this.saveMessage(request, "bibliographicReference.alreadyInSystem", accession, "Already in Gemma");
    } else {
        request.setAttribute("existsInSystem", Boolean.FALSE);
        try {
            bibRefFound = this.pubMedXmlFetcher.retrieveByHTTP(Integer.parseInt(accession));

            if (bibRefFound == null) {
                log.debug(accession + " not found in NCBI");

                result.rejectValue("accession", "bibliographicReference.notfoundInNCBI", "Not found in NCBI");
                return new ModelAndView("bibRefSearch", result.getModel());
            }

            this.saveMessage(request, "bibliographicReference.found", accession, "Found");

        } catch (NumberFormatException e) {
            result.rejectValue("accession", "error.integer", "Not a number");
            return new ModelAndView("bibRefSearch", result.getModel());
        }
    }

    status.setComplete();
    return new ModelAndView("bibRefView").addObject("bibliographicReference", bibRefFound);
}