cn.hxh.springside.utils.validator.ValidatorUtils.java Source code

Java tutorial

Introduction

Here is the source code for cn.hxh.springside.utils.validator.ValidatorUtils.java

Source

/**
 * Copyright (c) 2005-2011 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: Fixtures.java 1593 2011-05-11 10:37:12Z calvinxiu $
 */
package cn.hxh.springside.utils.validator;

import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;

import org.apache.commons.lang.StringUtils;

import com.google.common.collect.Lists;

/**
 * JSR303 Validator(Hibernate Validator).
 * 
 * @author badqiu
 * @author calvin
 */
public class ValidatorUtils {

    /**
     * JSR303validate, ?ConstraintViolationException.
     */
    public static void validateWithException(Validator validator, Object object, Class<?>... groups)
            throws ConstraintViolationException {
        Set constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            throw new ConstraintViolationException(constraintViolations);
        }
    }

    /**
     * , ?Set<ConstraintViolation>, separator.
     */
    public static String convertMessage(Set<? extends ConstraintViolation> constraintViolations, String separator) {
        List<String> errorMessages = Lists.newArrayList();
        for (ConstraintViolation violation : constraintViolations) {
            errorMessages.add(violation.getMessage());
        }
        return StringUtils.join(errorMessages, separator);
    }

    /**
     * , ?ConstraintViolationExceptionSet<ConstraintViolations>, separator.
     */
    public static String convertMessage(ConstraintViolationException e, String separator) {
        return convertMessage(e.getConstraintViolations(), separator);
    }

}