|
@@ -2,6 +2,7 @@ package com.chelvc.framework.common.validator;
|
|
|
|
|
|
import java.time.LocalDate;
|
|
|
import java.time.LocalDateTime;
|
|
|
+import java.util.Collection;
|
|
|
import java.util.Date;
|
|
|
import javax.validation.ConstraintValidator;
|
|
|
import javax.validation.ConstraintValidatorContext;
|
|
@@ -18,6 +19,40 @@ import com.chelvc.framework.common.util.DateUtils;
|
|
|
public class DateValidator implements ConstraintValidator<Dates, Object> {
|
|
|
private Dates annotation;
|
|
|
|
|
|
+ /**
|
|
|
+ * 日期对象转换
|
|
|
+ *
|
|
|
+ * @param value 参数值
|
|
|
+ * @return 日期对象实例
|
|
|
+ */
|
|
|
+ private Date convert(Object value) {
|
|
|
+ if (value instanceof Date) {
|
|
|
+ return (Date) value;
|
|
|
+ } else if (value instanceof LocalDate) {
|
|
|
+ return DateUtils.convert((LocalDate) value);
|
|
|
+ } else if (value instanceof LocalDateTime) {
|
|
|
+ return DateUtils.convert((LocalDateTime) value);
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 校验日期参数
|
|
|
+ *
|
|
|
+ * @param value 参数值
|
|
|
+ * @return true/false
|
|
|
+ */
|
|
|
+ private boolean validate(Object value) {
|
|
|
+ Date date = this.convert(value);
|
|
|
+ if (date == null) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ int min = this.annotation.min(), max = this.annotation.max();
|
|
|
+ long datetime = date.getTime(), now = System.currentTimeMillis();
|
|
|
+ return (min == Integer.MIN_VALUE || datetime >= now + min * 1000)
|
|
|
+ && (max == Integer.MAX_VALUE || datetime <= now + max * 1000);
|
|
|
+ }
|
|
|
+
|
|
|
@Override
|
|
|
public void initialize(Dates annotation) {
|
|
|
this.annotation = annotation;
|
|
@@ -25,18 +60,12 @@ public class DateValidator implements ConstraintValidator<Dates, Object> {
|
|
|
|
|
|
@Override
|
|
|
public boolean isValid(Object value, ConstraintValidatorContext context) {
|
|
|
- if (this.annotation == null
|
|
|
- || !(value instanceof Date || value instanceof LocalDate || value instanceof LocalDateTime)) {
|
|
|
- return true;
|
|
|
- }
|
|
|
- int min = this.annotation.min(), max = this.annotation.max();
|
|
|
- if (min == Integer.MIN_VALUE && max == Integer.MAX_VALUE) {
|
|
|
+ if (this.annotation == null || (this.annotation.min() == Integer.MIN_VALUE
|
|
|
+ && this.annotation.max() == Integer.MAX_VALUE)) {
|
|
|
return true;
|
|
|
+ } else if (value instanceof Collection) {
|
|
|
+ return ((Collection<?>) value).stream().allMatch(this::validate);
|
|
|
}
|
|
|
- Date date = value instanceof Date ? (Date) value : value instanceof LocalDate ?
|
|
|
- DateUtils.convert((LocalDate) value) : DateUtils.convert((LocalDateTime) value);
|
|
|
- long datetime = date.getTime(), now = System.currentTimeMillis();
|
|
|
- return (min == Integer.MIN_VALUE || datetime >= now + min * 1000)
|
|
|
- && (max == Integer.MAX_VALUE || datetime <= now + max * 1000);
|
|
|
+ return this.validate(value);
|
|
|
}
|
|
|
}
|