com.bixuebihui.db.MaxByteLengthValidator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of c-dbtools Show documentation
Show all versions of c-dbtools Show documentation
a fast small database connection pool and a active record flavor mini framework
package com.bixuebihui.db;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.constraints.Size;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
/**
* see 数据库字符串长度校验
* 如果数据库用的是utf8mb4则长度会限制更短。
*
* @author xingwx
* @version $Id: $Id
*/
public class MaxByteLengthValidator implements ConstraintValidator {
private static final String UTF_8="UTF-8";
private static final Logger LOG = LoggerFactory.getLogger(MaxByteLengthValidator.class);
private int max;
/**
* initialize.
*
* @param constraintAnnotation a {@link javax.validation.constraints.Size} object.
*/
@Override
public void initialize(Size constraintAnnotation) {
this.max = constraintAnnotation.max();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
try {
return object == null || object.getBytes(UTF_8).length <= this.max;
} catch (UnsupportedEncodingException e) {
LOG.error("isValid", e);
}
return false;
}
}