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.module.casereport.CaseReportValidator.java

/**
 * @see Validator#validate(Object, Errors)
 * @should fail if the case report object is null
 * @should fail if the patient is null/*from   w  ww .j  a v  a 2s  .c  om*/
 * @should fail if the report has no trigger added
 * @should fail for a new item if the patient already has an existing report item
 * @should pass for auto submit item with unique trigger and patient has existing item
 * @should pass for a valid case report
 */
@Override
public void validate(Object target, Errors errors) {
    if (target == null || !(target instanceof CaseReport)) {
        throw new IllegalArgumentException(
                "The parameter obj should not be null and must be of type" + getClass());
    }

    CaseReport caseReport = (CaseReport) target;
    ValidationUtils.rejectIfEmpty(errors, "patient", "casereports.error.patient.required");
    if (!errors.hasErrors()) {
        CaseReportService service = Context.getService(CaseReportService.class);
        if (caseReport.getId() == null && !caseReport.getAutoSubmitted()
                && service.getCaseReportByPatient(caseReport.getPatient()) != null) {
            errors.reject("casereports.error.patient.alreadyHasQueueItem");
        }
    }

    if (CollectionUtils.isEmpty(caseReport.getReportTriggers())) {
        errors.rejectValue("reportTriggers", "casereports.error.atleast.one.trigger.required");
    }

    if (!errors.hasErrors()) {
        int index = 0;
        for (CaseReportTrigger trigger : caseReport.getReportTriggers()) {
            try {
                errors.pushNestedPath("reportTriggers[" + index + "]");
                ValidationUtils.invokeValidator(triggerValidator, trigger, errors);
            } finally {
                errors.popNestedPath();
                index++;
            }
        }
    }

}

From source file:org.slc.sli.dashboard.web.util.ControllerInputValidatorAspect.java

/**
 * Validate param using param specific validator and validate all strings using a blacklist validator
 * @param arg/*from  w  w w.j av a2  s. co m*/
 * @param argName
 */
private void validateArg(Object arg, String argName) {
    BindingResult result = new BeanPropertyBindingResult(arg, argName);
    ValidationUtils.invokeValidator(getValidator(), arg, result);
    // force string validation for bad chars
    if (arg instanceof String) {
        ValidationUtils.invokeValidator(getValidator(), new DefaultStringValidatable((String) arg), result);
    }
    if (result.hasErrors()) {
        throw new HttpMessageConversionException("Invalid input parameter " + argName,
                new BindException(result));
    }
}

From source file:org.codeqinvest.web.project.ProjectValidator.java

private void validateSonarConnectionSettings(Project project, Errors errors) {
    if (project.getSonarConnectionSettings() != null) {
        try {// w  w w .  j  a v a  2  s. c  om
            errors.pushNestedPath("sonarConnectionSettings");
            ValidationUtils.invokeValidator(sonarConnectionSettingsValidator,
                    project.getSonarConnectionSettings(), errors);
        } finally {
            errors.popNestedPath();
        }
    }
}

From source file:org.codeqinvest.web.project.ProjectValidator.java

private void validateScmSettings(Project project, Errors errors) {
    if (project.getScmSettings() != null) {
        try {//from  ww  w . j a va  2 s .  c om
            errors.pushNestedPath("scmSettings");
            ValidationUtils.invokeValidator(scmConnectionSettingsValidator, project.getScmSettings(), errors);
        } finally {
            errors.popNestedPath();
        }
    }
}

From source file:com.springsource.greenhouse.signup.SignupController.java

private BindException validate(SignupForm form) {
    BindException errors;/*from  ww  w.j a v a  2s . c om*/
    errors = new BindException(form, "signupForm");
    LazyValidatorFactory lvf = new LazyValidatorFactory();
    Validator validator = new SpringValidatorAdapter(lvf.getValidator());
    ValidationUtils.invokeValidator(validator, form, errors);
    return errors;
}

From source file:org.codeqinvest.web.project.ProjectValidator.java

private void validateCodeChangeSettings(Project project, Errors errors) {
    if (project.getCodeChangeSettings() != null) {
        try {// w  w  w  . j a  v  a  2  s  .co m
            errors.pushNestedPath("codeChangeSettings");
            ValidationUtils.invokeValidator(codeChangeSettingsValidator, project.getCodeChangeSettings(),
                    errors);
        } finally {
            errors.popNestedPath();
        }
    }
}

From source file:com.google.ie.common.validation.IdeaValidator.java

@Override
public void validate(Object target, Errors errors) {
    Idea idea = (Idea) target;/*from   w  w w  .  j ava  2  s.  c o m*/
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, TITLE, IdeaExchangeErrorCodes.FIELD_REQUIRED,
            IdeaExchangeConstants.Messages.REQUIRED_FIELD);
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, DESCRIPTION, IdeaExchangeErrorCodes.FIELD_REQUIRED,
            IdeaExchangeConstants.Messages.REQUIRED_FIELD);

    if (!idea.isIdeaRightsGivenUp()) {
        errors.rejectValue(IDEA_RIGHTS_GIVEN_UP, IdeaExchangeErrorCodes.FIELD_ALWAYS_TRUE,
                IdeaExchangeConstants.Messages.FIELD_ALWAYS_TRUE);
        log.warn("Validation Error : " + IDEA_RIGHTS_GIVEN_UP + " -: "
                + IdeaExchangeConstants.Messages.FIELD_ALWAYS_TRUE);
    }
    if (!idea.isIpGivenUp()) {
        errors.rejectValue(IP_GIVEN_UP, IdeaExchangeErrorCodes.FIELD_ALWAYS_TRUE,
                IdeaExchangeConstants.Messages.FIELD_ALWAYS_TRUE);
        log.warn("Validation Error : " + IP_GIVEN_UP + " -: "
                + IdeaExchangeConstants.Messages.FIELD_ALWAYS_TRUE);
    }
    if (!StringUtils.isBlank(idea.getTitle()) && idea.getTitle().trim().length() > LENGTH_500) {
        errors.rejectValue(TITLE, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
        log.warn("Validation Error : " + TITLE + " -: "
                + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
    }
    if (!StringUtils.isBlank(idea.getDescription()) && idea.getDescription().trim().length() > LENGTH_3000) {
        errors.rejectValue(DESCRIPTION, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
        log.warn("Validation Error : " + DESCRIPTION + " -: "
                + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
    }
    if (!StringUtils.isBlank(idea.getIdeaSummary()) && idea.getIdeaSummary().trim().length() > LENGTH_3000) {
        errors.rejectValue(IDEA_SUMMARY, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
        log.warn("Validation Error : " + IDEA_SUMMARY + " -: "
                + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
    }
    if (!StringUtils.isBlank(idea.getMonetization()) && idea.getMonetization().trim().length() > LENGTH_500) {
        errors.rejectValue(MONETIZATION, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
        log.warn("Validation Error : " + MONETIZATION + " -: "
                + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
    }
    if (!StringUtils.isBlank(idea.getTargetAudience())
            && idea.getTargetAudience().trim().length() > LENGTH_500) {
        errors.rejectValue(TARGET_AUDIENCE, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
        log.warn("Validation Error : " + TARGET_AUDIENCE + " -: "
                + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
    }
    if (!StringUtils.isBlank(idea.getCompetition()) && idea.getCompetition().trim().length() > LENGTH_500) {
        errors.rejectValue(COMPETITION, IdeaExchangeErrorCodes.LENGTH_EXCEED_LIMIT,
                IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
        log.warn("Validation Error : " + COMPETITION + " -: "
                + IdeaExchangeConstants.Messages.LENGTH_EXCEED_LIMIT_MESSAGE);
    }
    if (idea.getTags() != null && idea.getTags().length() > ZERO) {
        ValidationUtils.invokeValidator(stringValidatorForTagTitle, idea.getTags(), errors);

    }
    if (log.isDebugEnabled()) {
        if (errors.hasErrors()) {
            log.debug("Validator found " + errors.getErrorCount() + " errors");
            for (Iterator<FieldError> iterator = errors.getFieldErrors().iterator(); iterator.hasNext();) {
                FieldError fieldError = iterator.next();
                log.debug("Error found in field: " + fieldError.getField() + " Message :"
                        + fieldError.getDefaultMessage());
            }
        } else {
            log.debug("Validator found no errors");
        }

    }
}

From source file:org.openmrs.web.controller.concept.ConceptReferenceTermFormController.java

/**
 * Processes requests to save/update a concept reference term
 *
 * @param request the {@link WebRequest} object
 * @param conceptReferenceTermModel the concept reference term object to save/update
 * @param result the {@link BindingResult} object
 * @return the url to redirect to/*from w  ww  . ja  v a2s  .co  m*/
 */
@RequestMapping(method = RequestMethod.POST, value = CONCEPT_REFERENCE_TERM_FORM_URL)
public String saveConceptReferenceTerm(WebRequest request,
        @ModelAttribute(value = "conceptReferenceTermModel") ConceptReferenceTermModel conceptReferenceTermModel,
        BindingResult result) {

    ConceptReferenceTerm conceptReferenceTerm = conceptReferenceTermModel.getConceptReferenceTerm();
    // add all the term maps
    //store ids of already mapped terms so that we don't map a term multiple times
    Set<Integer> mappedTermIds = null;
    for (int x = 0; x < conceptReferenceTermModel.getTermMaps().size(); x++) {
        if (mappedTermIds == null) {
            mappedTermIds = new HashSet<Integer>();
        }
        ConceptReferenceTermMap map = conceptReferenceTermModel.getTermMaps().get(x);

        if (map != null && map.getTermB() != null) {
            //skip past this mapping because its term is already in use by another mapping for this term
            if (!mappedTermIds.add(map.getTermB().getConceptReferenceTermId())) {
                continue;
            }

            if (request.getParameter("_termMaps[" + x + "].exists") == null) {
                // because of the _termMap[x].exists input name in the jsp, the value will be null for
                // deleted maps, remove the map.
                conceptReferenceTerm.removeConceptReferenceTermMap(map);
            } else {
                if (map.getConceptMapType() == null) {
                    result.rejectValue("termMaps[" + x + "]", "ConceptReferenceTerm.error.mapTypeRequired",
                            "Concept Map Type is required");
                    log.warn("Concept Map Type is required");
                    break;
                } else if (map.getTermB().equals(conceptReferenceTerm)) {
                    result.rejectValue("termMaps[" + x + "]", "ConceptReferenceTerm.map.sameTerm",
                            "Cannot map a concept reference term to itself");
                    log.warn("Cannot map a concept reference term to itself");
                    break;
                } else if (!conceptReferenceTerm.getConceptReferenceTermMaps().contains(map)) {
                    conceptReferenceTerm.addConceptReferenceTermMap(map);
                }
            }
        }
    }

    //if there are errors  with the term
    if (!result.hasErrors()) {
        try {
            result.pushNestedPath("conceptReferenceTerm");
            ValidationUtils.invokeValidator(new ConceptReferenceTermValidator(), conceptReferenceTerm, result);
            ValidationUtils.invokeValidator(new ConceptReferenceTermWebValidator(), conceptReferenceTerm,
                    result);
        } finally {
            result.popNestedPath();
        }
    }

    if (!result.hasErrors()) {
        try {
            conceptReferenceTerm = Context.getConceptService().saveConceptReferenceTerm(conceptReferenceTerm);
            if (log.isDebugEnabled()) {
                log.debug("Saved concept reference term: " + conceptReferenceTerm.toString());
            }
            request.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "ConceptReferenceTerm.saved",
                    WebRequest.SCOPE_SESSION);
            return "redirect:" + CONCEPT_REFERENCE_TERM_FORM_URL + ".form?conceptReferenceTermId="
                    + conceptReferenceTerm.getConceptReferenceTermId();
        } catch (APIException e) {
            log.error("Error while saving concept reference term", e);
            request.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "ConceptReferenceTerm.save.error",
                    WebRequest.SCOPE_SESSION);
        }
    }

    return CONCEPT_REFERENCE_TERM_FORM;
}

From source file:org.openmrs.web.controller.encounter.EncounterFormController.java

/**
 * @see org.springframework.web.servlet.mvc.SimpleFormController#processFormSubmission(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 *//*  w ww . j a v a 2s  .  c  o m*/
@Override
protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse reponse,
        Object obj, BindException errors) throws Exception {

    Encounter encounter = (Encounter) obj;

    try {
        if (Context.isAuthenticated()) {
            Context.addProxyPrivilege(PrivilegeConstants.GET_USERS);
            Context.addProxyPrivilege(PrivilegeConstants.GET_PATIENTS);

            if (encounter.getEncounterId() == null && StringUtils.hasText(request.getParameter("patientId"))) {
                encounter.setPatient(Context.getPatientService()
                        .getPatient(Integer.valueOf(request.getParameter("patientId"))));
            }
            if (encounter.isVoided()) {
                ValidationUtils.rejectIfEmptyOrWhitespace(errors, "voidReason", "error.null");
            }

            String[] providerIdsArray = ServletRequestUtils.getStringParameters(request, "providerIds");
            if (ArrayUtils.isEmpty(providerIdsArray)) {
                errors.reject("Encounter.provider.atleastOneProviderRequired");
            }

            String[] roleIdsArray = ServletRequestUtils.getStringParameters(request, "encounterRoleIds");

            ProviderService ps = Context.getProviderService();
            EncounterService es = Context.getEncounterService();
            if (providerIdsArray != null && roleIdsArray != null) {
                //list to store role provider mappings to be used below to detect removed providers
                List<String> unremovedRoleAndProviders = new ArrayList<String>();
                for (int i = 0; i < providerIdsArray.length; i++) {
                    if (StringUtils.hasText(providerIdsArray[i]) && StringUtils.hasText(roleIdsArray[i])) {
                        unremovedRoleAndProviders.add(roleIdsArray[i] + "-" + providerIdsArray[i]);
                        Provider provider = ps.getProvider(Integer.valueOf(providerIdsArray[i]));
                        EncounterRole encounterRole = es.getEncounterRole(Integer.valueOf(roleIdsArray[i]));
                        //if this is an existing provider, don't create a new one to avoid losing existing
                        //details like dateCreated, creator, uuid etc in the encounter_provider table
                        if (encounter.getProvidersByRole(encounterRole).contains(provider)) {
                            continue;
                        }

                        //this is a new provider
                        encounter.addProvider(encounterRole, provider);
                    }
                }
                //Get rid of the removed ones
                for (Map.Entry<EncounterRole, Set<Provider>> entry : encounter.getProvidersByRoles()
                        .entrySet()) {
                    for (Provider p : entry.getValue()) {
                        if (!unremovedRoleAndProviders
                                .contains(entry.getKey().getEncounterRoleId() + "-" + p.getProviderId())) {
                            encounter.removeProvider(entry.getKey(), p);
                        }
                    }
                }
            }

            ValidationUtils.invokeValidator(new EncounterValidator(), encounter, errors);
        }
    } finally {
        Context.removeProxyPrivilege(PrivilegeConstants.GET_USERS);
        Context.removeProxyPrivilege(PrivilegeConstants.GET_PATIENTS);
    }

    return super.processFormSubmission(request, reponse, encounter, errors);
}

From source file:com.hihsoft.baseclass.web.controller.BaseController.java

/**
 * Request. Spring MVCBind?,??//w  ww.j  a  va 2s  . co m
 * 
 * @return 
 * @see #preBind(HttpServletRequest,Object,ServletRequestDataBinder)
 */
protected BindingResult bindObject(final HttpServletRequest request, final Object command) throws Exception {
    Assert.notNull(command);

    // Binder
    final ServletRequestDataBinder binder = createBinder(request, command);
    // ?binder?,?binder?
    preBind(request, command, binder);

    // 
    binder.bind(request);

    // 
    final Validator[] validators = getValidators();
    if (validators != null) {
        for (final Validator validator : validators) {
            if (validator.supports(command.getClass())) {
                ValidationUtils.invokeValidator(validator, command, binder.getBindingResult());
            }
        }
    }
    return binder.getBindingResult();
}