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) 

Source Link

Document

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

Usage

From source file:org.openmrs.web.controller.report.ReportSchemaXmlFormController.java

/**
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 *//*  w w w  .  j av a2s.  co  m*/
public void validate(Object commandObject, Errors errors) {
    ValidationUtils.rejectIfEmpty(errors, "xml", "Paste XML for report before saving");
    ReportSchemaXml rsx = (ReportSchemaXml) commandObject;
    try {
        ReportService reportService = (ReportService) Context.getService(ReportService.class);
        ReportSchema schema = reportService.getReportSchema(rsx);
        if (schema == null)
            throw new NullPointerException();
    } catch (Exception ex) {
        log.warn("Exception building ReportSchema from XML", ex);
        if (ex.getCause() != null) {
            Throwable temp = ex.getCause();
            while (temp.getCause() != null) {
                temp = temp.getCause();
            }
            errors.rejectValue("xml", temp.getMessage());
        } else {
            StringBuilder sb = new StringBuilder();
            sb.append("Invalid XML content<br/>");
            sb.append(ex).append("<br/>");
            for (StackTraceElement e : ex.getStackTrace())
                sb.append(e.toString()).append("<br/>");
            errors.rejectValue("xml", sb.toString());
        }
    }
}

From source file:com.ccserver.digital.validator.CreditCardApplicationValidator.java

private void validateEmploymentTab(CreditCardApplicationDTO creditCardApplicationDTO, Errors errors) {
    if (creditCardApplicationDTO.getTypeOfEmployement() == TypeOfEmployment.Business) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "licenseNumber", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "businessStartDate", ErrorCodes.FIELD_REQUIRED);
        if (creditCardApplicationDTO.getBusinessStartDate() != null) {
            if (creditCardApplicationDTO.getBusinessStartDate().isAfter(LocalDateTime.now())) {
                errors.rejectValue("businessStartDate", ErrorCodes.FIELD_NOT_FUTURE);
            }//from www.j  a  v  a2  s.c  o  m
        }
        ValidationUtils.rejectIfEmpty(errors, "businessPhone", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "businessAddress", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "companyName", ErrorCodes.FIELD_REQUIRED);

    } else {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "nameOfEmployer", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "occupation", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "industry", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "employerAddress", ErrorCodes.FIELD_REQUIRED);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "businessTelephone", ErrorCodes.FIELD_REQUIRED);

        if ((creditCardApplicationDTO.getMonthsOfWorking() == null
                || creditCardApplicationDTO.getMonthsOfWorking() == 0)
                && (creditCardApplicationDTO.getYearsOfWorking() == null
                        || creditCardApplicationDTO.getYearsOfWorking() == 0)) {
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "monthsOfWorking", ErrorCodes.FIELD_REQUIRED);
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "yearsOfWorking", ErrorCodes.FIELD_REQUIRED);
        }
    }

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "monthlyIncome", ErrorCodes.FIELD_REQUIRED);
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "monthlyExpenses", ErrorCodes.FIELD_REQUIRED);

    if (creditCardApplicationDTO.getMonthlyExpenses() != null && creditCardApplicationDTO.getMonthlyExpenses()
            .compareTo(creditCardApplicationDTO.getMonthlyIncome()) > 0) {
        errors.rejectValue("monthlyExpenses", ErrorCodes.FIELD_INVALID);
    }
}

From source file:com.ssbusy.controller.checkout.CheckoutController.java

@SuppressWarnings("deprecation")
private MyAddress processShippingForm(MyShippingInfoForm shippingForm, BindingResult result) {
    shippingInfoFormValidator.validate(shippingForm, result);
    if (result.hasErrors())
        return null;
    // TODO ID?//from   w  w w  .  j  a v a 2 s. c  om
    // addressAddressLine3?dormitoryid??iddormitory??
    MyAddress myAddress = shippingForm.getMyAddress();
    Long dormitoryId;
    try {
        dormitoryId = Long.parseLong(myAddress.getAddressLine3());
    } catch (NumberFormatException e) {
        ValidationUtils.rejectIfEmpty(result, "myAddress.addressLine3", "addressLine3.required");
        return null;
    }
    if (myAddress.getDormitory() == null || !dormitoryId.equals(myAddress.getDormitory().getDormitoryId())) {
        Dormitory dormitory = dormitoryService.loadDormitotyById(dormitoryId);
        if (dormitory == null) {
            ValidationUtils.rejectIfEmpty(result, "myAddress.addressLine3", "addressLine3.required");
            return null;
        }
        // dormitory.id-1
        myAddress.setDormitory(dormitory);
    }

    myAddress.setAddressLine1("addressLine1");
    myAddress.setCity("city");
    myAddress.setPostalCode("310018");
    if (myAddress.getLastName() != null && myAddress.getLastName().length() > 30) {
        myAddress.setLastName(myAddress.getLastName().substring(0, 30));
    }
    myAddress.setState(shippingForm.getAddress().getState());
    if (myAddress.getCountry() == null)
        myAddress.setCountry(shippingForm.getAddress().getCountry());
    return myAddress;
}

From source file:com.tasktop.c2c.server.internal.tasks.domain.validation.AttachmentValidator.java

public void validate(Object target, Errors errors) {

    ValidationUtils.rejectIfEmpty(errors, "description", "field.required");
    ValidationUtils.rejectIfEmpty(errors, "filename", "field.required");
    ValidationUtils.rejectIfEmpty(errors, "mimeType", "field.required");

    Attachment attachment = (Attachment) target;

    if (attachment.getAttachmentData() == null || attachment.getAttachmentData().length == 0) {
        errors.rejectValue("attachmentData", "field.required");
    } else {/*from   w  w w . ja v  a2s .  c o  m*/

        int attachementSize = attachment.getAttachmentData().length;
        if (attachementSize > configuration.getMaxAttachmentSize()) {
            errors.rejectValue("attachmentData", "field.tooLarge",
                    new Object[] { FileUtils.byteCountToDisplaySize(configuration.getMaxAttachmentSize()) },
                    "Field to large");
        }
    }

    if (attachment.getFilename() != null) {
        int filenameSize = attachment.getFilename().length();
        if (filenameSize > configuration.getMaxAttachmentFilenameSize()) {
            errors.rejectValue("filename", "field.tooLarge",
                    new Object[] { configuration.getMaxAttachmentFilenameSize() }, "Field to large");
        }
    }
}

From source file:com.tasktop.c2c.server.internal.wiki.server.domain.validation.AttachmentValidator.java

@Override
public void validate(Object target, Errors errors) {
    Attachment attachment = (Attachment) target;

    ValidationUtils.rejectIfEmpty(errors, "page", "field.required");
    ValidationUtils.rejectIfEmpty(errors, "name", "field.required");
    if (attachment.getName() != null && !NAME_PATTERN.matcher(attachment.getName()).matches()) {
        errors.rejectValue("name", "invalidValue", new Object[] { attachment.getName() }, "invalid name");
    }/*www .ja va 2s.c o  m*/
    if (attachment.getMimeType() != null) {
        MediaType mediaType = null;
        try {
            mediaType = MediaType.parseMediaType(attachment.getMimeType());
        } catch (IllegalArgumentException e) {
            errors.rejectValue("mimeType", "invalidFormat");
        }
        if (mediaType != null) {
            if (mediaType.isWildcardType() || mediaType.isWildcardSubtype()) {
                errors.rejectValue("mimeType", "mediaTypeWildcardNotAllowed");
            } else if (!mediaTypes.isSupported(mediaType)) {
                errors.rejectValue("mimeType", "mediaTypeNotPermissible",
                        new Object[] { attachment.getMimeType() }, "bad mime type");
            }
        }
    }
    if (attachment.getContent() == null || attachment.getContent().length == 0) {
        errors.rejectValue("content", "field.required");
    } else {
        int attachementSize = attachment.getContent().length;
        if (attachementSize > configuration.getMaxAttachmentSize()) {
            errors.rejectValue("content", "field.tooLarge",
                    new Object[] { FileUtils.byteCountToDisplaySize(configuration.getMaxAttachmentSize()) },
                    "Field to large");
        }
    }
}

From source file:com.tasktop.c2c.server.scm.service.ScmRepositoryValidator.java

@Override
public void validate(Object target, Errors errors) {
    ValidationUtils.rejectIfEmpty(errors, "url", "field.required");
    ValidationUtils.rejectIfEmpty(errors, "type", "field.required");
    ValidationUtils.rejectIfEmpty(errors, "scmLocation", "field.required");

    ScmRepository repo = (ScmRepository) target;

    if (repo.getScmLocation().equals(ScmLocation.EXTERNAL) && repo.getUrl() != null
            && !repo.getUrl().startsWith("ssh:") && !urlValidator.isValid(repo.getUrl())) {
        errors.reject("url.invalid");
    }/* ww w.  ja v a2s .  c o m*/
}

From source file:cz.strmik.cmmitool.util.validator.OrganizationValidator.java

@Override
public void validate(Object target, Errors errors) {
    ValidationUtils.rejectIfEmpty(errors, "name", "field-required");
    Organization org = (Organization) target;
    if (!StringUtils.isEmpty(org.getEmail())) {
        Matcher emailMatcher = PATTERN_EMAIL.matcher(org.getEmail());
        if (!emailMatcher.matches()) {
            errors.rejectValue("email", "invalid-email");
        }/*w w  w .  j a  va 2s  . c  o m*/
    }
}

From source file:org.kuali.rice.ken.web.spring.AdministerNotificationRequestController.java

/**
 * This method handles approval/disapproval/acknowledgement of the notification request
 * @param request the HttpServletRequest
 * @param response the HttpServletResponse
 * @param command the command object bound for this MultiActionController
 * @throws ServletException/*from   w  w w  .  j a  va  2  s.c o m*/
 */
private void administerEventNotificationMessage(HttpServletRequest request, HttpServletResponse response,
        AdministerNotificationRequestCommand command, String action) throws ServletException {
    LOG.debug("remoteUser: " + request.getRemoteUser());

    BindException bindException = new BindException(command, "command");
    ValidationUtils.rejectIfEmpty(bindException, "docId", "Document id must be specified");
    if (bindException.hasErrors()) {
        throw new ServletRequestBindingException("Document id must be specified", bindException);
    }

    // obtain a workflow user object first
    //WorkflowIdDTO user = new WorkflowIdDTO(request.getRemoteUser());
    String userId = request.getRemoteUser();

    try {
        // now construct the workflow document, which will interact with workflow
        WorkflowDocument document = NotificationWorkflowDocument.loadNotificationDocument(userId,
                command.getDocId());

        NotificationBo notification = retrieveNotificationForWorkflowDocument(document);

        String initiatorPrincipalId = document.getInitiatorPrincipalId();
        Person initiator = KimApiServiceLocator.getPersonService().getPerson(initiatorPrincipalId);
        String notificationBlurb = notification.getContentType().getName() + " notification submitted by "
                + initiator.getName() + " for channel " + notification.getChannel().getName();
        if ("disapprove".equals(action)) {
            document.disapprove("User " + userId + " disapproving " + notificationBlurb);
        } else if ("approve".equals(action)) {
            document.approve("User " + userId + " approving " + notificationBlurb);
        } else if ("acknowledge".equals(action)) {
            document.acknowledge("User " + userId + " acknowledging " + notificationBlurb);
        }
    } catch (Exception e) {
        LOG.error("Exception occurred taking action on notification request", e);
        throw new ServletException("Exception occurred taking action on notification request", e);
    }
}

From source file:org.openmrs.module.conceptpubsub.web.bean.validator.ConfigureFormValidator.java

/**
 * @see org.springframework.validation.Validator#validate(java.lang.Object,
 *      org.springframework.validation.Errors)
 *//*from  w  ww  . j  a  va 2 s. c o m*/
@Override
public void validate(Object target, Errors errors) {
    ConfigureForm configureForm = (ConfigureForm) target;

    if (Boolean.TRUE.equals(configureForm.getAddLocalMappings())) {
        ValidationUtils.rejectIfEmpty(errors, "conceptSourceUuid", "conceptpubsub.error.emptyConceptSource");
    }

    if (!StringUtils.isBlank(configureForm.getConceptSourceUuid())) {
        ConceptSource source = Context.getService(ConceptService.class)
                .getConceptSourceByUuid(configureForm.getConceptSourceUuid());
        if (source == null) {
            errors.rejectValue("conceptSourceUuid", "conceptpubsub.error.missingConceptSource");
        }
    }

}

From source file:org.openmrs.module.radiology.order.RadiologyDiscontinuedOrderValidator.java

/**
 * Checks the form object for any inconsistencies/errors
 *
 * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
 * @should fail validation if order is null
 * @should fail validation if orderer is null
 * @should fail validation if orderReasonNonCoded is null
 * @should pass validation if all fields are correct
 *///from w w w .  j  a v a2 s .c  o m
public void validate(Object obj, Errors errors) {
    final Order order = (Order) obj;
    if (order == null) {
        errors.reject("error.general");
    } else {
        ValidationUtils.rejectIfEmpty(errors, "orderer", "error.null");
        ValidationUtils.rejectIfEmpty(errors, "orderReasonNonCoded", "error.null");
    }
}