All Downloads are FREE. Search and download functionalities are using the official Maven repository.

top.doudou.common.tool.utils.ParamUtil Maven / Gradle / Ivy

There is a newer version: 1.3.2
Show newest version
package top.doudou.common.tool.utils;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import top.doudou.base.exception.CustomException;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;
import java.util.stream.Collectors;

import static top.doudou.common.tool.constant.RegexConstant.EMAIL_REGEX;

/**
 * 验证参数
 *
 * @author  傻男人<[email protected]>
 * @date 2020-04-03
 */
@Slf4j
public class ParamUtil {

    /**
     * 检查入参是否有错误
     * @param result
     */
    public static void getErrorMsg(BindingResult result){
        if (result.hasErrors()) {
            throw new CustomException(result.getAllErrors().stream()
                    .map(DefaultMessageSourceResolvable::getDefaultMessage)
                    .collect(Collectors.joining(",")));
        }
    }

    /**
     * 检查入参是否有错误
     * @param result
     */
    public static void getFiledErrorMsg(BindingResult result){
        if (result.hasErrors()) {
            Map collect = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            throw new CustomException(new Gson().toJson(collect));
        }

    }

    /**
     * 参数验证
     *
     * @param t
     * @param 
     */
    public static  void checkParam(T t) {
        if (t == null) {
            throw new CustomException("参数不能为空");
        }
        Class clazz = t.getClass();
        Field[] fields = clazz.getDeclaredFields();
        try {
            for (Field field : fields) {
                if (Modifier.isStatic(field.getModifiers())) {
                    continue;
                }
                Annotation[] annotations = field.getDeclaredAnnotations();
                if (annotations.length == 0) {
                    continue;
                }
                if (!field.isAnnotationPresent(NotBlank.class) && !field.isAnnotationPresent(NotNull.class) && !field.isAnnotationPresent(Pattern.class) && !field.isAnnotationPresent(Email.class)) {
                    continue;
                }
                NotBlank notblank = field.getDeclaredAnnotation(NotBlank.class);
                Method method = clazz.getMethod("get" + acronymToUpper(field.getName()));
                Object value = method.invoke(t);
                if (notblank != null && null != value && StringUtils.isEmpty(value.toString())) {
                    throw new CustomException(notblank.message());
                }
                NotNull notNull = field.getDeclaredAnnotation(NotNull.class);
                if (notNull != null && null == value) {
                    throw new CustomException(notNull.message());
                }
                Pattern pattern = field.getDeclaredAnnotation(Pattern.class);
                if (pattern != null) {
                    if (value == null) {
                        throw new CustomException(pattern.message());
                    }
                    boolean matches = value.toString().matches(pattern.regexp());
                    if (!matches) {
                        throw new CustomException(pattern.message());
                    }
                }
                Email email = field.getDeclaredAnnotation(Email.class);
                if (email != null) {
                    if (value == null) {
                        throw new CustomException(email.message());
                    }
                    boolean matches = value.toString().matches(EMAIL_REGEX);
                    if (!matches) {
                        throw new CustomException("邮箱格式不正确");
                    }
                }
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new CustomException(e.getMessage());
        }
    }


    private static String acronymToUpper(String str) {
        char[] chars = str.toCharArray();
        if (chars[0] >= 'a' && chars[0] <= 'z') {
            chars[0] = (char) (chars[0] - 32);
        }
        return new String(chars);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy