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:co.adun.mvnejb3jpa.web.validation.IdentifyingNumberValidator.java

@Override
public void validate(Object target, Errors errors) {

    List<IdentifyingNumberModel> inList = (List<IdentifyingNumberModel>) target;

    /*//from   w ww  .j a  va 2 s . c o  m
     * Field names:
     * ltLeadsModel[0].identifyingNumberModel["+i+"].numberType.abbreviation
     * ltLeadsModel[0].identifyingNumberModel["+i+"].number
     * ltLeadsModel[0].identifyingNumberModel["+i+"].otherType
     * ltLeadsModel[0].identifyingNumberModel["+i+"].statusCode.abbreviation
     * ltLeadsModel
     * [0].identifyingNumberModel["+i+"].countryCode.abbreviation
     * ltLeadsModel
     * [0].identifyingNumberModel["+i+"].sourceCodes[0].abbreviation
     * ltLeadsModel[0].identifyingNumberModel["+i+"].comments
     * ltLeadsModel[0].identifyingNumberModel["+i+"].issueDate
     * ltLeadsModel[0].identifyingNumberModel["+i+"].expirationDate
     * ltLeadsModel[0].identifyingNumberModel["+i+"].eventDate
     * ltLeadsModel[0].identifyingNumberModel["+i+"].creationDate
     * ltLeadsModel[0].identifyingNumberModel["+i+"].updateDate
     * ltLeadsModel[0].identifyingNumberModel["+i+"].incidentDate
     * ltLeadsModel[0].identifyingNumberModel["+i+"].naturalizationDate
     */

    // retrieve DOB from lead model
    // Date dob = model.getBirthDateModel().getAsDate();

    String errorCode = "";
    int i = 0;

    for (IdentifyingNumberModel in : inList) {
        LtIdentifyingNumber ltIdentifyingNumber = in.getLtIdentifierNumber();
        if (ltIdentifyingNumber == null)
            continue;

        DateValueModel dateValueModel = in.getBirthDateModel();
        Date dob = dateValueModel.getAsDate();

        String numberType = in.getLtIdentifierNumber().getNumberTypeCode().getAbbreviation();

        // **************Global checks***************
        // - Number Type should not be default
        // - Check comment length (4000)
        // - Check source for not empty
        // Note: All dates are NOT required, but
        // an earlier-than-DOB check (if DOB is not null) must be done.

        if (numberType == "Select...") {
            errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].numberType.abbreviation",
                    errorCode, "Please select a Number Type.");
        }
        if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumberComment())
                && ltIdentifyingNumber.getIdentifyingNumberComment().length() > 4000) {
            errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].comments", errorCode,
                    "Comments must be 4000 characters or less.");
        }
        if (in.getSourceCodes().isEmpty()) {
            errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].sourceCodes[0].abbreviation",
                    errorCode, "Each IN must have at least one source.");
        }

        // *************Number-specific checks*************

        String pattern = "";

        // Alien Registration #
        if (numberType == "AR") {
            // number [9 numerics, not null]
            pattern = "^(\\d{9})$";
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && !ltIdentifyingNumber.getIdentifyingNumber().matches(pattern)) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Incorrect format [Alien Reg. #: 9 numerics]");
            }
        }
        // FIN
        else if (numberType == "FI") {
            // number [10 numerics, not null]
            pattern = "^(\\d{10})$";
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && !ltIdentifyingNumber.getIdentifyingNumber().matches(pattern)) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Incorrect format [FIN: 10 numerics]");
            }
        }
        // SSN
        else if (numberType == "SS") {
            // number [9 numerics input type ###-##-####, not null]
            pattern = "^(\\d{3}-\\d{2}-\\d{4})$";
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && !ltIdentifyingNumber.getIdentifyingNumber().matches(pattern)) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Incorrect format [SSN: ###-##-####]");
            }
        }
        // ADIS PID
        else if (numberType == "AD") {
            // number [9 numerics, not null]
            pattern = "^(\\d{9})$";
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && !ltIdentifyingNumber.getIdentifyingNumber().matches(pattern)) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Incorrect format [ADIS PID: 9 numerics]");
            }
        }
        // Credit Card
        else if (numberType == "CC") {
            // number [100 chars, not null]
            if (ltIdentifyingNumber.getIdentifyingNumber() == null) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number field cannot be null.");
            }
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && ltIdentifyingNumber.getIdentifyingNumber().length() > 100) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number must be 100 characters or less.");
            }
        }
        // ENFORCE Event
        else if (numberType == "EE") {
            // number [13 alphanumerics, not null]
            pattern = "^(\\w{9})$";
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && !ltIdentifyingNumber.getIdentifyingNumber().matches(pattern)) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Incorrect format [ENFORCE Event: 9 alphanumerics]");
            }
        }
        // LSID
        else if (numberType == "LS") {
            // number [100 chars, not null]
            if (ltIdentifyingNumber.getIdentifyingNumber() == null) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number field cannot be null.");
            }
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && ltIdentifyingNumber.getIdentifyingNumber().length() > 100) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number must be 100 characters or less.");
            }
        }
        // NUIN
        else if (numberType == "NU") {
            // number [100 chars, not null]
            if (ltIdentifyingNumber.getIdentifyingNumber() == null) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number field cannot be null.");
            }
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && ltIdentifyingNumber.getIdentifyingNumber().length() > 100) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number must be 100 characters or less.");
            }
        }
        // Other
        else if (numberType == "OT") {
            // other type [100 chars, not null]
            // number [100 chars, not null]
            if (ltIdentifyingNumber.getIdentifyingNumber() == null) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number field cannot be null.");
            }
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && ltIdentifyingNumber.getIdentifyingNumber().length() > 100) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number must be 100 characters or less.");
            }
        }
        // TSC
        else if (numberType == "TS") {
            // number [100 chars, not null]
            if (ltIdentifyingNumber.getIdentifyingNumber() == null) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number field cannot be null.");
            }
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && ltIdentifyingNumber.getIdentifyingNumber().length() > 100) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number must be 100 characters or less.");
            }
        }
        // TECS Case
        else if (numberType == "TC") {
            // number [14 alphanumerics, not null]
            // status [DD]
            pattern = "^(\\w{14})$";
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && !ltIdentifyingNumber.getIdentifyingNumber().matches(pattern)) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Incorrect format [TECS Case: 14 alphanumerics]");
            }
            if (ltIdentifyingNumber.getStatusCodeByTecsCaseStatusCodeId().getAbbreviation() != null
                    && ltIdentifyingNumber.getStatusCodeByTecsCaseStatusCodeId()
                            .getAbbreviation() == "Select...") {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].statusCode.abbreviation",
                        errorCode, "Status is required.");
            }
        }
        // Naturalization
        else if (numberType == "NA") {
            // number [100 chars, not null]
            // naturalization date [date]
            if (ltIdentifyingNumber.getIdentifyingNumber() == null) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number field cannot be null.");
            }
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && ltIdentifyingNumber.getIdentifyingNumber().length() > 100) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number must be 100 characters or less.");
            }
            DateValueModel naturalizationDateModel = in.getNaturalizationDate();
            ValidationUtils.invokeValidator(dateModelValidator, naturalizationDateModel, errors);
            Date naturalizationDate = naturalizationDateModel.getAsDate();
            if (dob != null && naturalizationDate != null && naturalizationDate.compareTo(dob) <= 0) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].naturalizationDate",
                        errorCode, "Naturalization Date should be later than lead's DOB.");
            }
        }
        // TECS ILOG
        else if (numberType == "TI") {
            // number [100 chars, not null]
            // incident date [date]
            if (ltIdentifyingNumber.getIdentifyingNumber() == null) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number field cannot be null.");
            }
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && ltIdentifyingNumber.getIdentifyingNumber().length() > 100) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number must be 100 characters or less.");
            }
            DateValueModel incidentDateModel = in.getIncidentDate();
            ValidationUtils.invokeValidator(dateModelValidator, incidentDateModel, errors);
            Date incidentDate = incidentDateModel.getAsDate();
            if (dob != null && incidentDate != null && incidentDate.compareTo(dob) <= 0) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].incidentDate", errorCode,
                        "Incident Date should be later than lead's DOB.");
            }
        }
        // TECS Subject Record
        else if (numberType == "TR") {
            // number [14 alphanumerics, not null]
            // status [DD]
            // creation date [date]
            // update date [date]
            pattern = "^(\\w{14})$";
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && !ltIdentifyingNumber.getIdentifyingNumber().matches(pattern)) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Incorrect format [TECS Subject Record: 14 alphanumerics]");
            }
            DateValueModel creationDateModel = in.getCreationDate();
            ValidationUtils.invokeValidator(dateModelValidator, creationDateModel, errors);
            Date creationDate = creationDateModel.getAsDate();
            if (dob != null && creationDate != null && creationDate.compareTo(dob) <= 0) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].creationDate", errorCode,
                        "Creation Date should be later than lead's DOB.");
            }
            DateValueModel updateDateModel = in.getUpdateDate();
            ValidationUtils.invokeValidator(dateModelValidator, updateDateModel, errors);
            Date updateDate = updateDateModel.getAsDate();
            if (dob != null && updateDate != null && updateDate.compareTo(dob) <= 0) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].updateDate", errorCode,
                        "Update Date should be later than lead's DOB.");
            }
        }
        // Passport
        else if (numberType == "PA") {
            // number [100 chars, not null]
            // country [DD]
            // issue date [date]
            // expiration date [date]
            if (ltIdentifyingNumber.getIdentifyingNumber() == null) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number field cannot be null.");
            }
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && ltIdentifyingNumber.getIdentifyingNumber().length() > 100) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number must be 100 characters or less.");
            }
            DateValueModel issueDateModel = in.getIssueDate();
            ValidationUtils.invokeValidator(dateModelValidator, issueDateModel, errors);
            Date issueDate = issueDateModel.getAsDate();
            if (dob != null && issueDate != null && issueDate.compareTo(dob) <= 0) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].issueDate", errorCode,
                        "Issue Date should be later than lead's DOB.");
            }
            DateValueModel expirationDateModel = in.getExpirationDate();
            ValidationUtils.invokeValidator(dateModelValidator, expirationDateModel, errors);
            Date expirationDate = expirationDateModel.getAsDate();
            if (dob != null && expirationDate != null && expirationDate.compareTo(dob) <= 0) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].expirationDate",
                        errorCode, "Expiration Date should be later than lead's DOB.");
            }
        }
        // Visa
        else if (numberType == "VI") {
            // number [8 alphanumerics, not null]
            // issue date [date]
            // expiration date [date]
            pattern = "^(\\w{8})$";
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && !ltIdentifyingNumber.getIdentifyingNumber().matches(pattern)) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Incorrect format [Visa: 8 alphanumerics]");
            }
            DateValueModel issueDateModel = in.getIssueDate();
            ValidationUtils.invokeValidator(dateModelValidator, issueDateModel, errors);
            Date issueDate = issueDateModel.getAsDate();
            if (dob != null && issueDate != null && issueDate.compareTo(dob) <= 0) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].issueDate", errorCode,
                        "Issue Date should be later than lead's DOB.");
            }
            DateValueModel expirationDateModel = in.getExpirationDate();
            ValidationUtils.invokeValidator(dateModelValidator, expirationDateModel, errors);
            Date expirationDate = expirationDateModel.getAsDate();
            if (dob != null && expirationDate != null && expirationDate.compareTo(dob) <= 0) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].expirationDate",
                        errorCode, "Expiration Date should be later than lead's DOB.");
            }
        }
        // Driver's License
        else if (numberType == "DL") {
            // number [100 chars, not null]
            // country [DD]
            // issue date [date]
            // expiration date [date]
            if (ltIdentifyingNumber.getIdentifyingNumber() == null) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number field cannot be null.");
            }
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && ltIdentifyingNumber.getIdentifyingNumber().length() > 100) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number must be 100 characters or less.");
            }
            DateValueModel issueDateModel = in.getIssueDate();
            ValidationUtils.invokeValidator(dateModelValidator, issueDateModel, errors);
            Date issueDate = issueDateModel.getAsDate();
            if (dob != null && issueDate != null && issueDate.compareTo(dob) <= 0) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].issueDate", errorCode,
                        "Issue Date should be later than lead's DOB.");
            }
            DateValueModel expirationDateModel = in.getExpirationDate();
            ValidationUtils.invokeValidator(dateModelValidator, expirationDateModel, errors);
            Date expirationDate = expirationDateModel.getAsDate();
            if (dob != null && expirationDate != null && expirationDate.compareTo(dob) <= 0) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].expirationDate",
                        errorCode, "Expiration Date should be later than lead's DOB.");
            }
        }
        // State ID Card
        else if (numberType == "SI") {
            // number [100 chars, not null]
            // country [DD]
            // issue date [date]
            // expiration date [date]
            if (ltIdentifyingNumber.getIdentifyingNumber() == null) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number field cannot be null.");
            }
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && ltIdentifyingNumber.getIdentifyingNumber().length() > 100) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number must be 100 characters or less.");
            }
            DateValueModel issueDateModel = in.getIssueDate();
            ValidationUtils.invokeValidator(dateModelValidator, issueDateModel, errors);
            Date issueDate = issueDateModel.getAsDate();
            if (dob != null && issueDate != null && issueDate.compareTo(dob) <= 0) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].issueDate", errorCode,
                        "Issue Date should be later than lead's DOB.");
            }
            DateValueModel expirationDateModel = in.getExpirationDate();
            ValidationUtils.invokeValidator(dateModelValidator, expirationDateModel, errors);
            Date expirationDate = expirationDateModel.getAsDate();
            if (dob != null && expirationDate != null && expirationDate.compareTo(dob) <= 0) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].expirationDate",
                        errorCode, "Expiration Date should be later than lead's DOB.");
            }
        }
        // FAA License
        else if (numberType == "FA") {
            // number [100 chars, not null]
            // issue date [date]
            // expiration date [date]
            if (ltIdentifyingNumber.getIdentifyingNumber() == null) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number field cannot be null.");
            }
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && ltIdentifyingNumber.getIdentifyingNumber().length() > 100) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number must be 100 characters or less.");
            }
            DateValueModel issueDateModel = in.getIssueDate();
            ValidationUtils.invokeValidator(dateModelValidator, issueDateModel, errors);
            Date issueDate = issueDateModel.getAsDate();
            if (dob != null && issueDate != null && issueDate.compareTo(dob) <= 0) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].issueDate", errorCode,
                        "Issue Date should be later than lead's DOB.");
            }
            DateValueModel expirationDateModel = in.getExpirationDate();
            ValidationUtils.invokeValidator(dateModelValidator, expirationDateModel, errors);
            Date expirationDate = expirationDateModel.getAsDate();
            if (dob != null && expirationDate != null && expirationDate.compareTo(dob) <= 0) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].expirationDate",
                        errorCode, "Expiration Date should be later than lead's DOB.");
            }
        }
        // Visa Control
        else if (numberType == "VC") {
            // number [100 chars, not null]
            // event date [date]
            if (ltIdentifyingNumber.getIdentifyingNumber() == null) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number field cannot be null.");
            }
            if (!StringUtils.isEmpty(ltIdentifyingNumber.getIdentifyingNumber())
                    && ltIdentifyingNumber.getIdentifyingNumber().length() > 100) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].number", errorCode,
                        "Number must be 100 characters or less.");
            }
            DateValueModel eventDateModel = in.getEventDate();
            ValidationUtils.invokeValidator(dateModelValidator, eventDateModel, errors);
            Date eventDate = eventDateModel.getAsDate();
            if (dob != null && eventDate != null && eventDate.compareTo(dob) <= 0) {
                errors.rejectValue("ltLeadsModel[0].identifyingNumberModel[" + i + "].eventDate", errorCode,
                        "Event Date should be later than lead's DOB.");
            }
        }
        i++;
    }
}

From source file:org.openmrs.web.controller.visit.VisitFormController.java

private void validateEncounter(Encounter e, BindingResult result) {
    Errors encounterErrors = new BindException(e, "encounter");
    ValidationUtils.invokeValidator(new EncounterValidator(), e, encounterErrors);
    if (encounterErrors.hasErrors()) {
        //bind the errors to the model object
        for (ObjectError error : encounterErrors.getAllErrors()) {
            result.reject(error.getCode(), error.getArguments(), error.getDefaultMessage());
        }// www.jav  a  2  s .c  om
    }
}

From source file:com.jd.survey.web.survey.SurveyPageValidator.java

@Override
public void validate(Object obj, Errors errors) {
    SurveyPage surveyPage = (SurveyPage) obj;

    QuestionAnswerValidator questionAnswerValidator;
    int i = 0;/*  w w w .  ja v  a2  s . com*/
    for (QuestionAnswer questionAnswer : surveyPage.getQuestionAnswers()) {
        log.info("Validating question answer" + questionAnswer.getQuestion().getQuestionText());
        errors.pushNestedPath("questionAnswers[" + i + "]");
        questionAnswerValidator = new QuestionAnswerValidator(dateFormat, validcontentTypes, validImageTypes,
                maximunFileSize, invalidContentMessage, invalidFileSizeMessage);
        ValidationUtils.invokeValidator(questionAnswerValidator, questionAnswer, errors);
        errors.popNestedPath();
        i++;
    }
}

From source file:edu.northwestern.bioinformatics.studycalendar.xml.validators.ActivityXMLValidatorTest.java

public void testValidate() {
    BindException errors = new BindException(valid, StringUtils.EMPTY);
    ValidationUtils.invokeValidator(SPRING_ACTIVITY_VALIDATOR_INSTANCE, valid, errors);

    assertFalse(errors.hasErrors());/* w w w. j  a  va2s  .com*/
}

From source file:edu.northwestern.bioinformatics.studycalendar.xml.validators.ActivityXMLValidatorTest.java

public void testInvalid() {
    BindException errors = new BindException(invalid, StringUtils.EMPTY);
    ValidationUtils.invokeValidator(SPRING_ACTIVITY_VALIDATOR_INSTANCE, invalid, errors);

    assertTrue(errors.hasErrors());//from ww  w  .  j  av  a  2s.  c o m
    assertEquals("Wrong error count", 1, errors.getErrorCount());
    assertEquals("Wrong error code", "error.file.not.valid", errors.getGlobalError().getCode());
}

From source file:org.nextframework.controller.MultiActionController.java

protected void validate(WebRequestContext request, Object command, ServletRequestDataBinder binder) {

    if (!suppressValidation(request, command)) {
        BindException errors = new BindException(binder.getBindingResult());
        if (request.getAttribute(NextCommonsMultipartResolver.MAXUPLOADEXCEEDED) != null) {
            errors.reject("", "O tamanho mximo de upload de arquivos (10M) foi excedido");
        }/*from   ww w  . j a v  a  2  s.  c o m*/
        ObjectAnnotationValidator objectAnnotationValidator = new ObjectAnnotationValidator(
                ServiceFactory.getService(ValidatorRegistry.class), request.getServletRequest());
        objectAnnotationValidator.validate(command, errors);
        String acao = request.getParameter(ACTION_PARAMETER);
        validate(command, errors, acao);
        if (this.validators != null) {
            for (int i = 0; i < this.validators.length; i++) {
                if (this.validators[i].supports(command.getClass())) {
                    ValidationUtils.invokeValidator(this.validators[i], command, errors);
                }
            }
        }
    }
}

From source file:org.openmrs.module.kenyaui.form.ValidatingCommandObject.java

/**
 * Validates the given field using the given validator
 * @param errors the bind errors//from  w ww.j  av a  2  s.  c o  m
 * @param field the field name
 * @param validator the validator
 */
public void validateField(Errors errors, String field, Validator validator) {
    Object value = errors.getFieldValue(field);

    // Don't validate null values
    if (value == null) {
        return;
    }

    errors.pushNestedPath(field);

    if (validator != null) {
        ValidationUtils.invokeValidator(validator, value, errors);
    } else {
        // Use a registered OpenMRS validator
        ValidateUtil.validate(value, errors);
    }

    errors.popNestedPath();
}

From source file:org.openmrs.validator.ConceptValidator.java

/**
 * Checks that a given concept object is valid.
 *
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 * @should pass if the concept has atleast one fully specified name added to it
 * @should fail if there is a duplicate unretired concept name in the locale
 * @should fail if there is a duplicate unretired preferred name in the same locale
 * @should fail if there is a duplicate unretired fully specified name in the same locale
 * @should fail if any names in the same locale for this concept are similar
 * @should pass if the concept with a duplicate name is retired
 * @should pass if the concept being validated is retired and has a duplicate name
 * @should fail if any name is an empty string
 * @should fail if the object parameter is null
 * @should pass if the concept is being updated with no name change
 * @should fail if any name is a null value
 * @should not allow multiple preferred names in a given locale
 * @should not allow multiple fully specified conceptNames in a given locale
 * @should not allow multiple short names in a given locale
 * @should not allow an index term to be a locale preferred name
 * @should fail if there is no name explicitly marked as fully specified
 * @should pass if the duplicate ConceptName is neither preferred nor fully Specified
 * @should pass if the concept has a synonym that is also a short name
 * @should fail if a term is mapped multiple times to the same concept
 * @should not fail if a term has two new mappings on it
 * @should fail if there is a duplicate unretired concept name in the same locale different than
 *         the system locale//from   ww  w . j  av a  2 s.  c o m
 * @should pass for a new concept with a map created with deprecated concept map methods
 * @should pass for an edited concept with a map created with deprecated concept map methods
 * @should pass validation if field lengths are correct
 * @should fail validation if field lengths are not correct
 * @should pass if fully specified name is the same as short name
 * @should pass if different concepts have the same short name
 */
public void validate(Object obj, Errors errors) throws APIException, DuplicateConceptNameException {

    if (obj == null || !(obj instanceof Concept)) {
        throw new IllegalArgumentException(
                "The parameter obj should not be null and must be of type" + Concept.class);
    }

    Concept conceptToValidate = (Concept) obj;
    //no name to validate, but why is this the case?
    if (conceptToValidate.getNames().size() == 0) {
        errors.reject("Concept.name.atLeastOneRequired");
        return;
    }

    boolean hasFullySpecifiedName = false;
    for (Locale conceptNameLocale : conceptToValidate.getAllConceptNameLocales()) {
        boolean fullySpecifiedNameForLocaleFound = false;
        boolean preferredNameForLocaleFound = false;
        boolean shortNameForLocaleFound = false;
        Set<String> validNamesFoundInLocale = new HashSet<String>();
        Collection<ConceptName> namesInLocale = conceptToValidate.getNames(conceptNameLocale);
        for (ConceptName nameInLocale : namesInLocale) {
            if (StringUtils.isBlank(nameInLocale.getName())) {
                log.debug("Name in locale '" + conceptNameLocale.toString()
                        + "' cannot be an empty string or white space");
                errors.reject("Concept.name.empty");
            }
            if (nameInLocale.isLocalePreferred() != null) {
                if (nameInLocale.isLocalePreferred() && !preferredNameForLocaleFound) {
                    if (nameInLocale.isIndexTerm()) {
                        log.warn("Preferred name in locale '" + conceptNameLocale.toString()
                                + "' shouldn't be an index term");
                        errors.reject("Concept.error.preferredName.is.indexTerm");
                    } else if (nameInLocale.isShort()) {
                        log.warn("Preferred name in locale '" + conceptNameLocale.toString()
                                + "' shouldn't be a short name");
                        errors.reject("Concept.error.preferredName.is.shortName");
                    } else if (nameInLocale.isVoided()) {
                        log.warn("Preferred name in locale '" + conceptNameLocale.toString()
                                + "' shouldn't be a voided name");
                        errors.reject("Concept.error.preferredName.is.voided");
                    }

                    preferredNameForLocaleFound = true;
                }
                //should have one preferred name per locale
                else if (nameInLocale.isLocalePreferred() && preferredNameForLocaleFound) {
                    log.warn("Found multiple preferred names in locale '" + conceptNameLocale.toString() + "'");
                    errors.reject("Concept.error.multipleLocalePreferredNames");
                }
            }

            if (nameInLocale.isFullySpecifiedName()) {
                if (!hasFullySpecifiedName) {
                    hasFullySpecifiedName = true;
                }
                if (!fullySpecifiedNameForLocaleFound) {
                    fullySpecifiedNameForLocaleFound = true;
                } else {
                    log.warn("Found multiple fully specified names in locale '" + conceptNameLocale.toString()
                            + "'");
                    errors.reject("Concept.error.multipleFullySpecifiedNames");
                }
                if (nameInLocale.isVoided()) {
                    log.warn("Fully Specified name in locale '" + conceptNameLocale.toString()
                            + "' shouldn't be a voided name");
                    errors.reject("Concept.error.fullySpecifiedName.is.voided");
                }
            }

            if (nameInLocale.isShort()) {
                if (!shortNameForLocaleFound) {
                    shortNameForLocaleFound = true;
                }
                //should have one short name per locale
                else {
                    log.warn("Found multiple short names in locale '" + conceptNameLocale.toString() + "'");
                    errors.reject("Concept.error.multipleShortNames");
                }
            }

            //find duplicate names for a non-retired concept
            if (Context.getConceptService().isConceptNameDuplicate(nameInLocale)) {
                throw new DuplicateConceptNameException("'" + nameInLocale.getName()
                        + "' is a duplicate name in locale '" + conceptNameLocale.toString() + "'");
            }

            //
            if (errors.hasErrors()) {
                log.debug("Concept name '" + nameInLocale.getName() + "' for locale '" + conceptNameLocale
                        + "' is invalid");
                //if validation fails for any conceptName in current locale, don't proceed
                //This helps not to have multiple messages shown that are identical though they might be
                //for different conceptNames
                return;
            }

            //No duplicate names allowed for the same locale and concept, keep the case the same
            //except for short names
            if (!nameInLocale.isShort() && !validNamesFoundInLocale.add(nameInLocale.getName().toLowerCase())) {
                throw new DuplicateConceptNameException(
                        "'" + nameInLocale.getName() + "' is a duplicate name in locale '"
                                + conceptNameLocale.toString() + "' for the same concept");
            }

            if (log.isDebugEnabled()) {
                log.debug("Valid name found: " + nameInLocale.getName());
            }
        }
    }

    //Ensure that each concept has atleast a fully specified name
    if (!hasFullySpecifiedName) {
        log.debug("Concept has no fully specified name");
        errors.reject("Concept.error.no.FullySpecifiedName");
    }

    if (CollectionUtils.isNotEmpty(conceptToValidate.getConceptMappings())) {
        //validate all the concept maps
        int index = 0;
        Set<Integer> mappedTermIds = null;
        for (ConceptMap map : conceptToValidate.getConceptMappings()) {
            if (map.getConceptReferenceTerm().getConceptReferenceTermId() == null) {
                //if this term is getting created on the fly e.g. from old legacy code, validate it
                try {
                    errors.pushNestedPath("conceptMappings[" + index + "].conceptReferenceTerm");
                    ValidationUtils.invokeValidator(new ConceptReferenceTermValidator(),
                            map.getConceptReferenceTerm(), errors);
                } finally {
                    errors.popNestedPath();
                }

            }
            /*if (map.getConceptMapType() == null) {
               errors.rejectValue("conceptMappings[" + index + "].conceptMapType", "Concept.map.typeRequired",
                   "The concept map type is required for a concept map");
               return;
            }*/

            //don't proceed to the next maps since the current one already has errors
            if (errors.hasErrors()) {
                return;
            }

            if (mappedTermIds == null) {
                mappedTermIds = new HashSet<Integer>();
            }

            //if we already have a mapping to this term, reject it this map
            if (map.getConceptReferenceTerm().getId() != null
                    && !mappedTermIds.add(map.getConceptReferenceTerm().getId())) {
                errors.rejectValue("conceptMappings[" + index + "]", "ConceptReferenceTerm.term.alreadyMapped",
                        "Cannot map a reference term multiple times to the same concept");
            }

            index++;
        }
    }
    ValidateUtil.validateFieldLengths(errors, obj.getClass(), "version", "retireReason");
}

From source file:org.openmrs.validator.DrugValidator.java

/**
 * Validates an Drug object/*  w  ww  . j a  v a2 s .  c  o m*/
 * 
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 * @should fail if the drug object is null
 * @should fail if drug on drugReferenceMap is null
 * @should fail if conceptReferenceTerm on drugReferenceMap is null
 * @should invoke ConceptReferenceTermValidator if term on drugReferenceMap is new
 * @should invoke ConceptMapTypeValidator if conceptMapType on drugReferenceMap is new
 * @should pass if all fields are correct
 * @should reject drug multiple mappings to the same term
 * @should pass validation if field lengths are correct
 * @should fail validation if field lengths are not correct
 */
@Override
public void validate(Object obj, Errors errors) {
    if (obj == null || !(obj instanceof Drug)) {
        throw new IllegalArgumentException(
                "The parameter obj should not be null and must be of type" + Drug.class);
    } else {
        Drug drug = (Drug) obj;
        Set<DrugReferenceMap> drugReferenceMaps = drug.getDrugReferenceMaps();
        Set<String> mappedTermUuids = new HashSet<String>();
        int index = 0;
        for (DrugReferenceMap referenceMap : drugReferenceMaps) {
            Drug mappedDrug = referenceMap.getDrug();
            ConceptReferenceTerm referenceTerm = referenceMap.getConceptReferenceTerm();
            ConceptMapType mapType = referenceMap.getConceptMapType();

            if (mappedDrug == null) {
                errors.rejectValue("drugReferenceMaps[" + index + "].drug", "Drug.drugReferenceMap.mappedDrug");
            }
            if (referenceTerm == null) {
                errors.rejectValue("drugReferenceMaps[" + index + "].conceptReferenceTerm",
                        "Drug.drugReferenceMap.conceptReferenceTerm");
            } else if (referenceTerm.getConceptReferenceTermId() == null) {
                try {
                    errors.pushNestedPath("drugReferenceMaps[" + index + "].conceptReferenceTerm");
                    ValidationUtils.invokeValidator(new ConceptReferenceTermValidator(), referenceTerm, errors);
                } finally {
                    errors.popNestedPath();
                }
            }

            if (mapType == null) {
                errors.rejectValue("drugReferenceMaps[" + index + "].conceptMapType",
                        "Drug.drugReferenceMap.conceptMapType");
            } else if (mapType.getConceptMapTypeId() == null) {
                try {
                    errors.pushNestedPath("drugReferenceMaps[" + index + "].conceptMapType");
                    ValidationUtils.invokeValidator(new ConceptMapTypeValidator(), mapType, errors);
                } finally {
                    errors.popNestedPath();
                }
            }

            //don't proceed to the next map
            if (errors.hasErrors()) {
                return;
            }

            //if we already have a mapping to this term, reject it this map
            if (!mappedTermUuids.add(referenceMap.getConceptReferenceTerm().getUuid())) {
                errors.rejectValue("drugReferenceMaps[" + index + "].conceptReferenceTerm",
                        "Drug.drugReferenceMap.termAlreadyMapped",
                        "Cannot map a drug multiple times to the same reference term");
            }
            index++;
        }
        ValidateUtil.validateFieldLengths(errors, obj.getClass(), "name", "retireReason", "strength");
    }
}