package com.cscec.pms.safety.impl.facade.util;
import com.cscec.pms.safety.impl.exception.SafetyExceptionType;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.yyc.ycloud.base.support.utils.AssertUtils;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.BeanUtils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class CheckParamsUtil {
private static final Cache<String, String> cache;
private static final String EMPTY = "";
private static final String SEGMENTATION = ".";
private static final String REMINDER = "不能為空";
static {
cache = CacheBuilder.newBuilder()
.expireAfterAccess(30, TimeUnit.MINUTES)
.recordStats()
.maximumSize(64)
.build();
}
public static void checkParam(Object param, String... ignoreFields) {
Class<?> classes = param.getClass();
PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(classes);
for (PropertyDescriptor targetPd : targetPds) {
Method readMethod = targetPd.getReadMethod();
if (Arrays.stream(ignoreFields).anyMatch(field -> targetPd.getName().equals(field)))
continue;
try {
String message = cache.get(classes.getName() + SEGMENTATION + targetPd.getName(), () -> {
try {
ApiModelProperty annotation = classes.getDeclaredField(targetPd.getName()).getAnnotation(io.swagger.annotations.ApiModelProperty.class);
return annotation != null ? annotation.value() + REMINDER : EMPTY;
} catch (NoSuchFieldException e) {
return EMPTY;
}
});
Object o = readMethod.invoke(param);
AssertUtils.notNull(o, SafetyExceptionType.PARAM_ERROR, message);
if (o instanceof String)
AssertUtils.hasLength(o.toString(), SafetyExceptionType.PARAM_ERROR, message);
if (o instanceof Collection)
AssertUtils.notEmpty((Collection<?>) o, SafetyExceptionType.PARAM_ERROR, message);
if (o instanceof Map)
AssertUtils.notEmpty((Map<?, ?>) o, SafetyExceptionType.PARAM_ERROR, message);
}catch (Exception e){
throw new RuntimeException(e);
}
}
}
}