Example usage for org.springframework.validation ValidationUtils rejectIfEmpty

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

Introduction

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

Prototype

public static void rejectIfEmpty(Errors errors, String field, String errorCode, Object[] errorArgs) 

Source Link

Document

Reject the given field with the given error code and error arguments if the value is empty.

Usage

From source file:org.grouter.presentation.controller.user.UserEditCommandValidator.java

public void validate(Object object, Errors errors) {
    UserEditCommand userEditCommand = (UserEditCommand) object;

    // All errors are specified in message property files
    ValidationUtils.rejectIfEmpty(errors, "user.userName", "userEditCommand.user.userName",
            "Username is required.");
    ValidationUtils.rejectIfEmpty(errors, "user.password", "userEditCommand.user.password",
            "Password is required.");
    ValidationUtils.rejectIfEmpty(errors, "user.firstName", "userEditCommand.user.firstName",
            "Firstname is required.");
    ValidationUtils.rejectIfEmpty(errors, "user.userRoles", "userEditCommand.user.userRoles",
            "A user must have at least one role.");
    ValidationUtils.rejectIfEmpty(errors, "user.address.email", "userEditCommand.user.address.email",
            "Email is required.");

    if (!EmailValidator.getInstance().isValid(userEditCommand.getUser().getAddress().getEmail())) {
        errors.rejectValue("user.address.email", "userEditCommand.user.address.emailInvalid",
                "Email is invalid.");
    }// w ww  .ja  va 2s.com

    if (userEditCommand.getUser().getUserRoles() == null
            || userEditCommand.getUser().getUserRoles().size() == 0) {
        errors.rejectValue("user.userRoles", "userEditCommand.user.userRoles", "Email is invalid.");

    }
}

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

/**
 * Validates the given Encounter. Currently checks if the patient has been set and also ensures
 * that the patient for an encounter and the visit it is associated to if any, are the same.
 *
 * @param obj The encounter to validate.
 * @param errors Errors//from w  w  w .  j  av  a 2  s  .  co  m
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 * @should fail if the patients for the visit and the encounter dont match
 * @should fail if patient is not set
 * @should fail if encounter type is not set
 * @should fail if encounter dateTime is not set
 * @should fail if encounter dateTime is after current dateTime
 * @should fail if encounter dateTime is before visit startDateTime
 * @should fail if encounter dateTime is after visit stopDateTime
 * @should pass validation if field lengths are correct
 * @should fail validation if field lengths are not correct
 */
public void validate(Object obj, Errors errors) throws APIException {
    if (log.isDebugEnabled()) {
        log.debug(this.getClass().getName() + ".validate...");
    }

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

    Encounter encounter = (Encounter) obj;

    ValidationUtils.rejectIfEmpty(errors, "encounterType", "Encounter.error.encounterType.required",
            "Encounter type is Required");

    ValidationUtils.rejectIfEmpty(errors, "patient", "Encounter.error.patient.required", "Patient is required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "encounterDatetime", "Encounter.datetime.required");
    if (encounter.getVisit() != null
            && !ObjectUtils.equals(encounter.getVisit().getPatient(), encounter.getPatient())) {
        errors.rejectValue("visit", "Encounter.visit.patients.dontMatch",
                "The patient for the encounter and visit should be the same");
    }

    Date encounterDateTime = encounter.getEncounterDatetime();

    if (encounterDateTime != null && encounterDateTime.after(new Date())) {
        errors.rejectValue("encounterDatetime", "Encounter.datetimeShouldBeBeforeCurrent",
                "The encounter datetime should be before the current date.");
    }

    Visit visit = encounter.getVisit();
    if (visit != null && encounterDateTime != null) {
        if (visit.getStartDatetime() != null && encounterDateTime.before(visit.getStartDatetime())) {
            errors.rejectValue("encounterDatetime", "Encounter.datetimeShouldBeInVisitDatesRange",
                    "The encounter datetime should be between the visit start and stop dates.");
        }

        if (visit.getStopDatetime() != null && encounterDateTime.after(visit.getStopDatetime())) {
            errors.rejectValue("encounterDatetime", "Encounter.datetimeShouldBeInVisitDatesRange",
                    "The encounter datetime should be between the visit start and stop dates.");
        }
    }
    ValidateUtil.validateFieldLengths(errors, obj.getClass(), "voidReason");
}

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

/**
 * Validates the given PatientProgram./*from  w w  w.j  a  v a  2s .co  m*/
 *
 * @param obj The patient program to validate.
 * @param errors Errors
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 * @should fail validation if obj is null
 * @should fail if the patient field is blank
 * @should fail if there is more than one patientState with the same states and startDates
 * @should fail if there is more than one state with a null start date in the same workflow
 * @should pass if the start date of the first patient state in the work flow is null
 * @should fail if any patient state has an end date before its start date
 * @should fail if the program property is null
 * @should fail if any patient states overlap each other in the same work flow
 * @should fail if a patientState has an invalid work flow state
 * @should fail if a patient program has duplicate states in the same work flow
 * @should fail if a patient is in multiple states in the same work flow
 * @should fail if a enrolled date is in future at the date it set
 * @should fail if a completion date is in future at the date it set
 * @should fail if a patient program has an enroll date after its completion
 * @should pass if a patient is in multiple states in different work flows
 * @should pass for a valid program
 * @should pass for patient states that have the same start dates in the same work flow
 * @should pass validation if field lengths are correct
 * @should fail validation if field lengths are not correct
 */
public void validate(Object obj, Errors errors) {
    if (log.isDebugEnabled()) {
        log.debug(this.getClass().getName() + ".validate...");
    }

    if (obj == null) {
        throw new IllegalArgumentException("The parameter obj should not be null");
    }
    MessageSourceService mss = Context.getMessageSourceService();
    PatientProgram patientProgram = (PatientProgram) obj;
    ValidationUtils.rejectIfEmpty(errors, "patient", "error.required",
            new Object[] { mss.getMessage("general.patient") });
    ValidationUtils.rejectIfEmpty(errors, "program", "error.required",
            new Object[] { mss.getMessage("Program.program") });

    if (errors.hasErrors()) {
        return;
    }

    ValidationUtils.rejectIfEmpty(errors, "dateEnrolled", "error.patientProgram.enrolledDateEmpty");

    Date today = new Date();
    if (patientProgram.getDateEnrolled() != null && today.before(patientProgram.getDateEnrolled())) {
        errors.rejectValue("dateEnrolled", "error.patientProgram.enrolledDateDateCannotBeInFuture");
    }

    if (patientProgram.getDateCompleted() != null && today.before(patientProgram.getDateCompleted())) {
        errors.rejectValue("dateCompleted", "error.patientProgram.completionDateCannotBeInFuture");
    }

    // if enrollment or complete date of program is in future or complete date has come before enroll date we should throw error
    if (patientProgram.getDateEnrolled() != null && OpenmrsUtil
            .compareWithNullAsLatest(patientProgram.getDateCompleted(), patientProgram.getDateEnrolled()) < 0) {
        errors.rejectValue("dateCompleted", "error.patientProgram.enrolledDateShouldBeBeforecompletionDate");
    }

    Set<ProgramWorkflow> workFlows = patientProgram.getProgram().getWorkflows();
    //Patient state validation is specific to a work flow
    for (ProgramWorkflow workFlow : workFlows) {
        Set<PatientState> patientStates = patientProgram.getStates();
        if (patientStates != null) {
            //Set to store to keep track of unique valid state and start date combinations
            Set<String> statesAndStartDates = new HashSet<String>();
            PatientState latestState = null;
            boolean foundCurrentPatientState = false;
            boolean foundStateWithNullStartDate = false;
            for (PatientState patientState : patientStates) {
                if (patientState.isVoided()) {
                    continue;
                }

                String missingRequiredFieldCode = null;
                //only the initial state can have a null start date
                if (patientState.getStartDate() == null) {
                    if (foundStateWithNullStartDate) {
                        missingRequiredFieldCode = "general.dateStart";
                    } else {
                        foundStateWithNullStartDate = true;
                    }
                } else if (patientState.getState() == null) {
                    missingRequiredFieldCode = "State.state";
                }

                if (missingRequiredFieldCode != null) {
                    errors.rejectValue("states", "PatientState.error.requiredField",
                            new Object[] { mss.getMessage(missingRequiredFieldCode) }, null);
                    return;
                }

                //state should belong to one of the workflows in the program
                // note that we are iterating over getAllWorkflows() here because we want to include
                // retired workflows, and the workflows variable does not include retired workflows
                boolean isValidPatientState = false;
                for (ProgramWorkflow wf : patientProgram.getProgram().getAllWorkflows()) {
                    if (wf.getStates().contains(patientState.getState())) {
                        isValidPatientState = true;
                        break;
                    }
                }

                if (!isValidPatientState) {
                    errors.rejectValue("states", "PatientState.error.invalidPatientState",
                            new Object[] { patientState }, null);
                    return;
                }

                //will validate it with other states in its workflow
                if (!patientState.getState().getProgramWorkflow().equals(workFlow)) {
                    continue;
                }

                if (OpenmrsUtil.compareWithNullAsLatest(patientState.getEndDate(),
                        patientState.getStartDate()) < 0) {
                    errors.rejectValue("states", "PatientState.error.endDateCannotBeBeforeStartDate");
                    return;
                } else if (statesAndStartDates
                        .contains(patientState.getState().getUuid() + "" + patientState.getStartDate())) {
                    // we already have a patient state with the same work flow state and start date
                    errors.rejectValue("states", "PatientState.error.duplicatePatientStates");
                    return;
                }

                //Ensure that the patient is only in one state at a given time
                if (!foundCurrentPatientState && patientState.getEndDate() == null) {
                    foundCurrentPatientState = true;
                } else if (foundCurrentPatientState && patientState.getEndDate() == null) {
                    errors.rejectValue("states", "PatientProgram.error.cannotBeInMultipleStates");
                    return;
                }

                if (latestState == null) {
                    latestState = patientState;
                } else {
                    if (patientState.compareTo(latestState) > 0) {
                        //patient should have already left this state since it is older
                        if (latestState.getEndDate() == null) {
                            errors.rejectValue("states", "PatientProgram.error.cannotBeInMultipleStates");
                            return;
                        } else if (OpenmrsUtil.compareWithNullAsEarliest(patientState.getStartDate(),
                                latestState.getEndDate()) < 0) {
                            //current state was started before a previous state was ended
                            errors.rejectValue("states", "PatientProgram.error.foundOverlappingStates",
                                    new Object[] { patientState.getStartDate(), latestState.getEndDate() },
                                    null);
                            return;
                        }
                        latestState = patientState;
                    } else if (patientState.compareTo(latestState) < 0) {
                        //patient should have already left this state since it is older
                        if (patientState.getEndDate() == null) {
                            errors.rejectValue("states", "PatientProgram.error.cannotBeInMultipleStates");
                            return;
                        } else if (OpenmrsUtil.compareWithNullAsEarliest(latestState.getStartDate(),
                                patientState.getEndDate()) < 0) {
                            //latest state was started before a previous state was ended
                            errors.rejectValue("states", "PatientProgram.error.foundOverlappingStates");
                            return;
                        }
                    }
                }

                statesAndStartDates.add(patientState.getState().getUuid() + "" + patientState.getStartDate());
            }
        }
    }
    ValidateUtil.validateFieldLengths(errors, obj.getClass(), "voidReason");
    //
}

From source file:org.uhp.portlets.news.web.SuperUserController.java

@Override
protected void validatePage(Object command, Errors errors, int page, boolean finish) {

    switch (page) {
    case 0://from  w  w w . ja v  a  2s  .c  om
        ValidationUtils.rejectIfEmpty(errors, "token", "TOKEN_IS_REQUIRED", "Token is required.");
        break;
    case 1:
        ValidationUtils.rejectIfEmpty(errors, "user.userId", "USERID_REQUIRED", "User should be selected.");
        break;

    }

}

From source file:org.uhp.portlets.news.web.validator.ItemValidator.java

public void validateTitle(final ItemForm itemForm, final Errors errors) {
    ValidationUtils.rejectIfEmpty(errors, "item.title", "ITEM_TITLE_REQUIRED", "Title is required.");
}

From source file:org.uhp.portlets.news.web.validator.ItemValidator.java

public void validateMessage(final ItemForm item, final Errors errors) {
    ValidationUtils.rejectIfEmpty(errors, "item.body", "ITEM_MSG_REQUIRED", "Message is required.");
}

From source file:org.uhp.portlets.news.web.validator.PermissionValidator.java

public void validateTokenAndRole(final PermForm permForm, final Errors errors) {
    ValidationUtils.rejectIfEmpty(errors, "token", "TOKEN_REQUIRED", "Token is required.");
    ValidationUtils.rejectIfEmpty(errors, "role", "ROLE_REQUIRED", "Role should be selected.");
}

From source file:org.uhp.portlets.news.web.validator.PermissionValidator.java

public void validateUser(final PermForm permForm, final Errors errors) {
    ValidationUtils.rejectIfEmpty(errors, "user.userId", "USERID_REQUIRED", "User should be selected.");

}