Example usage for org.springframework.validation ValidationUtils invokeValidator

List of usage examples for org.springframework.validation ValidationUtils invokeValidator

Introduction

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

Prototype

public static void invokeValidator(Validator validator, Object target, Errors errors) 

Source Link

Document

Invoke the given Validator for the supplied object and Errors instance.

Usage

From source file:org.openmrs.web.controller.patient.ShortPatientFormValidator.java

/**
 * Validates the given Patient.//www.ja  v  a 2  s.c  o  m
 *
 * @param obj The patient to validate.
 * @param errors The patient to validate.
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 * @should pass if the minimum required fields are provided and are valid
 * @should fail validation if gender is blank
 * @should fail validation if birthdate is blank
 * @should fail validation if birthdate makes patient 120 years old or older
 * @should fail validation if birthdate is a future date
 * @should fail validation if causeOfDeath is blank when patient is dead
 * @should fail if all name fields are empty or white space characters
 * @should fail if no identifiers are added
 * @should fail if all identifiers have been voided
 * @should fail if any name has more than 50 characters
 * @should fail validation if deathdate is a future date
 * @should fail if the deathdate is before the birthdate incase the patient is dead
 * @should reject a duplicate name
 * @should reject a duplicate address
 */
public void validate(Object obj, Errors errors) {
    if (log.isDebugEnabled()) {
        log.debug(this.getClass().getName() + ": Validating patient data from the short patient form....");
    }

    ShortPatientModel shortPatientModel = (ShortPatientModel) obj;
    PersonName personName = shortPatientModel.getPersonName();

    //TODO We should be able to let developers and implementations to specify which person name 
    // fields should be used to determine uniqueness

    //check if this name has a unique givenName, middleName and familyName combination
    for (PersonName possibleDuplicate : shortPatientModel.getPatient().getNames()) {
        //don't compare the name to itself
        if (OpenmrsUtil.nullSafeEquals(possibleDuplicate.getId(), personName.getId())) {
            continue;
        }

        if (OpenmrsUtil.nullSafeEqualsIgnoreCase(possibleDuplicate.getGivenName(), personName.getGivenName())
                && OpenmrsUtil.nullSafeEqualsIgnoreCase(possibleDuplicate.getMiddleName(),
                        personName.getMiddleName())
                && OpenmrsUtil.nullSafeEqualsIgnoreCase(possibleDuplicate.getFamilyName(),
                        personName.getFamilyName())) {
            errors.reject("Patient.duplicateName", new Object[] { personName.getFullName() },
                    personName.getFullName() + " is a duplicate name for the same patient");
        }
    }

    Errors nameErrors = new BindException(personName, "personName");
    new PersonNameValidator().validatePersonName(personName, nameErrors, false, true);

    if (nameErrors.hasErrors()) {
        // pick all the personName errors and bind them to the formObject
        Iterator<ObjectError> it = nameErrors.getAllErrors().iterator();
        Set<String> errorCodesWithNoArguments = new HashSet<String>();
        while (it.hasNext()) {
            ObjectError error = it.next();
            // don't show similar error message multiple times in the view
            // unless they take in arguments which will make them atleast different
            if (error.getCode() != null && (!errorCodesWithNoArguments.contains(error.getCode())
                    || (error.getArguments() != null && error.getArguments().length > 0))) {
                errors.reject(error.getCode(), error.getArguments(), "");
                if (error.getArguments() == null || error.getArguments().length == 0) {
                    errorCodesWithNoArguments.add(error.getCode());
                }
            }
        }
        // drop the collection
        errorCodesWithNoArguments = null;
    }

    //TODO We should be able to let developers and implementations to specify which
    // person address fields should be used to determine uniqueness

    //check if this address is unique
    PersonAddress personAddress = shortPatientModel.getPersonAddress();
    for (PersonAddress possibleDuplicate : shortPatientModel.getPatient().getAddresses()) {
        //don't compare the address to itself
        if (OpenmrsUtil.nullSafeEquals(possibleDuplicate.getId(), personAddress.getId())) {
            continue;
        }

        if (!possibleDuplicate.isBlank() && !personAddress.isBlank()
                && possibleDuplicate.toString().equalsIgnoreCase(personAddress.toString())) {
            errors.reject("Patient.duplicateAddress", new Object[] { personAddress.toString() },
                    personAddress.toString() + " is a duplicate address for the same patient");
        }
    }

    //check if all required addres fields are filled
    errors.pushNestedPath("personAddress");
    new PersonAddressValidator().validate(personAddress, errors);
    errors.popNestedPath();
    if (errors.hasErrors()) {
        return;
    }

    int index = 0;
    if (CollectionUtils.isEmpty(shortPatientModel.getIdentifiers())) {
        errors.reject("PatientIdentifier.error.insufficientIdentifiers");
    } else {
        boolean nonVoidedIdentifierFound = false;
        for (PatientIdentifier pId : shortPatientModel.getIdentifiers()) {
            //no need to validate unsaved identifiers that have been removed
            if (pId.getPatientIdentifierId() == null && pId.isVoided()) {
                continue;
            }

            if (!pId.isVoided()) {
                nonVoidedIdentifierFound = true;
            }
            errors.pushNestedPath("identifiers[" + index + "]");
            new PatientIdentifierValidator().validate(pId, errors);
            errors.popNestedPath();
            index++;
        }
        // if all the names are voided
        if (!nonVoidedIdentifierFound) {
            errors.reject("PatientIdentifier.error.insufficientIdentifiers");
        }

    }

    // Make sure they chose a gender
    if (StringUtils.isBlank(shortPatientModel.getPatient().getGender())) {
        errors.rejectValue("patient.gender", "Person.gender.required");
    }

    // check patients birthdate against future dates and really old dates
    if (shortPatientModel.getPatient().getBirthdate() != null) {
        if (shortPatientModel.getPatient().getBirthdate().after(new Date())) {
            errors.rejectValue("patient.birthdate", "error.date.future");
        } else {
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.YEAR, -120); // patient cannot be older than 120
            // years old
            if (shortPatientModel.getPatient().getBirthdate().before(c.getTime())) {
                errors.rejectValue("patient.birthdate", "error.date.nonsensical");
            }
        }
    } else {
        errors.rejectValue("patient.birthdate", "error.required",
                new Object[] { Context.getMessageSourceService().getMessage("Person.birthdate") }, "");
    }

    //validate the personAddress
    if (shortPatientModel.getPersonAddress() != null) {
        try {
            errors.pushNestedPath("personAddress");
            ValidationUtils.invokeValidator(new PersonAddressValidator(), shortPatientModel.getPersonAddress(),
                    errors);
        } finally {
            errors.popNestedPath();
        }
    }

    if (shortPatientModel.getPatient().getDead()) {
        if (shortPatientModel.getPatient().getCauseOfDeath() == null) {
            errors.rejectValue("patient.causeOfDeath", "Person.dead.causeOfDeathNull");
        }

        if (shortPatientModel.getPatient().getDeathDate() != null) {
            if (shortPatientModel.getPatient().getDeathDate().after(new Date())) {
                errors.rejectValue("patient.deathDate", "error.date.future");
            }
            // death date has to be after birthdate if both are specified
            if (shortPatientModel.getPatient().getBirthdate() != null && shortPatientModel.getPatient()
                    .getDeathDate().before(shortPatientModel.getPatient().getBirthdate())) {
                errors.rejectValue("patient.deathDate", "error.deathdate.before.birthdate");
            }
        }
    }
}

From source file:org.opentestsystem.authoring.testauth.validation.ComputationRuleValidator.java

@Override
public void validate(final Object obj, final Errors errors) {
    // execute JSR-303 validations (annotations)
    this.jsrValidator.validate(obj, errors);

    final ComputationRule computationRule = (ComputationRule) obj;
    if (!CollectionUtils.isEmpty(computationRule.getParameters())) {
        // custom validation for each computationRuleParameter
        for (int i = 0; i < computationRule.getParameters().size(); i++) {
            final ComputationRuleParameter nextParameter = computationRule.getParameters().get(i);
            try {
                errors.pushNestedPath(PARAMETERS + "[" + i + "]");
                ValidationUtils.invokeValidator(this.computationRuleParameterValidator, nextParameter, errors);

                if (nextParameter.getPosition() > computationRule.getParameters().size()) {
                    rejectValue(errors, "position", getErrorMessageRoot() + PARAMETERS_POSITION + MSG_INVALID,
                            nextParameter.getPosition());
                }/*from  w  w w.j  a  v  a  2 s . c o  m*/
            } finally {
                errors.popNestedPath();
            }
        }

        // check for duplicate parameter names
        final Map<String, Collection<ComputationRuleParameter>> duplicates = Maps.filterEntries(
                Multimaps.index(computationRule.getParameters(), PARAMETER_TO_NAME_TRANSFORMER).asMap(),
                PARAMETER_DUPLICATE_FILTER);
        if (!duplicates.isEmpty()) {
            rejectValue(errors, PARAMETERS, getErrorMessageRoot() + PARAMETERS_NAME + MSG_DUPLICATES,
                    duplicates.keySet().toString());
        }

        // check for duplicate parameter position
        final Map<String, Collection<ComputationRuleParameter>> duplicatePositions = Maps.filterEntries(
                Multimaps.index(computationRule.getParameters(), PARAMETER_TO_POSITION_TRANSFORMER).asMap(),
                PARAMETER_DUPLICATE_FILTER);
        if (!duplicatePositions.isEmpty()) {
            rejectValue(errors, PARAMETERS, getErrorMessageRoot() + PARAMETERS_POSITION + MSG_DUPLICATES,
                    duplicatePositions.keySet().toString());
        } else if (!errors.hasErrors()) {
            computationRule.setParameters(
                    Lists.newArrayList(Ordering.natural().onResultOf(PARAMETER_TO_POSITION_TRANSFORMER)
                            .sortedCopy(computationRule.getParameters())));
        }
    }
    if (StringUtils.trimToNull(computationRule.getVersion()) != null) {
        final String[] parts = computationRule.getVersion().split("\\.");
        if (parts.length != 2) { // not the right number version parts
            // should be 2 parts like "1.0"
            rejectValue(errors, "version", "version.format", new Object() {
            });
            return;
        }
        if (NumberUtils.toInt(parts[0], -1) < 1 || parts[1].length() > 1
                || (NumberUtils.toInt(parts[1], -1) < 0 || NumberUtils.toInt(parts[1], -1) > 9)) { //major is a negative number or some other character
            rejectValue(errors, "version", "version.majorminor.format", new Object() {
            });
        }
    }
}

From source file:org.opentestsystem.authoring.testauth.validation.ItemSelectionAlgorithmValidator.java

@Override
public void validate(final Object obj, final Errors errors) {
    // execute JSR-303 validations (annotations)
    this.jsrValidator.validate(obj, errors);

    final ItemSelectionAlgorithm algorithm = (ItemSelectionAlgorithm) obj;
    if (algorithm.getParameters() != null) {
        // custom validation for each itemSelectionAlgorithmParameter
        for (int i = 0; i < algorithm.getParameters().size(); i++) {
            final ItemSelectionAlgorithmParameter nextParameter = algorithm.getParameters().get(i);
            try {
                errors.pushNestedPath(PARAMETERS_FIELD + "[" + i + "]");
                ValidationUtils.invokeValidator(this.itemSelectionAlgorithmParameterValidator, nextParameter,
                        errors);/*w w  w. j a  va2  s . c o  m*/

                if (nextParameter.getPosition() > algorithm.getParameters().size()) {
                    rejectValue(errors, "position",
                            getErrorMessageRoot() + PARAMETERS_POSITION_FIELD + MSG_INVALID,
                            nextParameter.getPosition());
                }
            } finally {
                errors.popNestedPath();
            }
        }

        // check if parameters have duplicate names
        final Map<String, Collection<ItemSelectionAlgorithmParameter>> duplicates = Maps.filterEntries(
                Multimaps.index(algorithm.getParameters(),
                        ITEM_SELECTION_ALGORITHM_PARAMETER_TO_NAME_TRANSFORMER).asMap(),
                ITEM_SELECTION_ALGORITHM_PARAMETER_DUPLICATE_FILTER);
        if (!duplicates.isEmpty()) {
            rejectValue(errors, PARAMETERS_FIELD,
                    getErrorMessageRoot() + PARAMETERS_NAME_FIELD + MSG_DUPLICATES,
                    duplicates.keySet().toString());
        }

        // check if parameters have duplicate position
        final Map<String, Collection<ItemSelectionAlgorithmParameter>> duplicatePositions = Maps.filterEntries(
                Multimaps.index(algorithm.getParameters(),
                        ITEM_SELECTION_ALGORITHM_PARAMETER_TO_POSITION_TRANSFORMER).asMap(),
                ITEM_SELECTION_ALGORITHM_PARAMETER_DUPLICATE_FILTER);
        if (!duplicatePositions.isEmpty()) {
            rejectValue(errors, PARAMETERS_FIELD,
                    getErrorMessageRoot() + PARAMETERS_POSITION_FIELD + MSG_DUPLICATES,
                    duplicatePositions.keySet().toString());
        }
    }
    if (StringUtils.trimToNull(algorithm.getVersion()) != null) {
        String[] parts = algorithm.getVersion().split("\\.");
        if (parts.length != 2) { //not the right number version parts
            //should be 2 parts like "1.0"
            rejectValue(errors, "version", "version.format", new Object() {
            });
            return;
        }
        if (NumberUtils.toInt(parts[0], -1) < 1 || parts[1].length() > 1
                || (NumberUtils.toInt(parts[1], -1) < 0 || NumberUtils.toInt(parts[1], -1) > 9)) { //major is a negative number or some other character
            rejectValue(errors, "version", "version.majorminor.format", new Object() {
            });
        }
    }

    if (!errors.hasErrors()) {
        algorithm.trimParameterValues();
    }
}

From source file:org.opentestsystem.delivery.testreg.rest.FileUploadDataController.java

/**
 * Validates a file given its format and gridFsId.
 *
 * @param gridFsId/*from   w w  w  . j ava  2 s  .  c  o  m*/
 *        A {@link ModelAttribute} whose value is bound from the request mapping variables.
 * @param result
 *        An interface for binding results of all forms of validation
 * @param response
 *        HttpServletResponse for sending HTTP-specific responses
 * @return Returns {@link FileValidationResult}
 * @throws Exception
 */
@RequestMapping(value = "/validateFile/{gridFsId}", method = RequestMethod.GET, produces = {
        MediaType.APPLICATION_JSON_VALUE })
@Secured({ "ROLE_Accommodations Upload", "ROLE_Student Upload", "ROLE_Entity Upload",
        "ROLE_StudentGroup Upload", "ROLE_User Upload", "ROLE_ExplicitEligibility Upload" })
@ResponseBody
public List<FileValidationResult> validate(@ModelAttribute("gridFsId") final String gridFsId,
        final BindingResult result, final HttpServletResponse response) throws Exception {

    final long start = System.currentTimeMillis();
    final GridFSDBFile file = getGridFSDBFile(gridFsId);
    this.metricClient.sendPerformanceMetricToMna(buildMetricMessage(gridFsId, "validateFile->getGridFSDBFile"),
            System.currentTimeMillis() - start);

    long startMarker = System.currentTimeMillis();

    final List<FileValidationResult> returnList = Lists.newArrayList();

    // fileType cannot be null
    final FileType fileType = FileType.findByFilename(file.getFilename());
    // throws IllegalArgumentException when no enum is found from file-extension
    final UploadFileParser<Map<String, List<DataRecord>>> fileParser = this.fileParserMap.get(fileType);
    ParserResult<Map<String, List<DataRecord>>> parsedResult = null;
    try {
        parsedResult = fileParser.parse(file.getInputStream(), retrieveFormatTypeFromFileMetadata(file));
    } catch (final LocalizedException loc) {
        final FileValidationResult validationResult = new FileValidationResult();
        validationResult.addError(new ValidationMessage("Invalid File type: " + loc.getLocalizedMessage(),
                ValidationMessageType.FATAL_ERROR));
        returnList.add(validationResult);
        return returnList;
    }
    this.metricClient.sendPerformanceMetricToMna(buildMetricMessage(gridFsId, "validateFile->file parse"),
            System.currentTimeMillis() - startMarker);

    if (parsedResult.isEmpty()) {
        final FileValidationResult validationResult = new FileValidationResult();
        validationResult
                .addError(new ValidationMessage("Invalid File type", ValidationMessageType.FATAL_ERROR));
        returnList.add(validationResult);
        return returnList;
    }

    startMarker = System.currentTimeMillis();
    ValidationUtils.invokeValidator(this.fileUploadValidator, parsedResult.getParsedObject(), result);
    this.metricClient.sendPerformanceMetricToMna(buildMetricMessage(gridFsId, "validateFile->validation"),
            System.currentTimeMillis() - startMarker);

    if (result.hasErrors()) {
        Integer errorCountThresh = null;
        try {
            errorCountThresh = Integer.parseInt(this.errorCountThreshold);
        } catch (final NumberFormatException e) {
            errorCountThresh = DEFAULT_ERROR_THRESHOLD;
        }
        returnList.addAll(ValidationHelper.transform(result, errorCountThresh));
    }
    this.metricClient.sendPerformanceMetricToMna(buildMetricMessage(gridFsId, "validateFile->total time"),
            System.currentTimeMillis() - start);
    return returnList;
}

From source file:org.springframework.web.servlet.mvc.multiaction.MultiActionController.java

/**
 * Bind request parameters onto the given command bean
 * @param request request from which parameters will be bound
 * @param command command object, that must be a JavaBean
 * @throws Exception in case of invalid state or arguments
 *///from  ww w. ja  v  a  2s .c om
protected void bind(HttpServletRequest request, Object command) throws Exception {
    logger.debug("Binding request parameters onto MultiActionController command");
    ServletRequestDataBinder binder = createBinder(request, command);
    binder.bind(request);
    if (this.validators != null) {
        for (Validator validator : this.validators) {
            if (validator.supports(command.getClass())) {
                ValidationUtils.invokeValidator(validator, command, binder.getBindingResult());
            }
        }
    }
    binder.closeNoCatch();
}