聊聊dubbo的ValidationFilter

本文主要研究一下dubbo的ValidationFilter

ValidationFilter

dubbo-2.7.2/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java

@Activate(group = {CONSUMER, PROVIDER}, value = VALIDATION_KEY, order = 10000)
public class ValidationFilter implements Filter {

    private Validation validation;

    /**
     * Sets the validation instance for ValidationFilter
     * @param validation Validation instance injected by dubbo framework based on "validation" attribute value.
     */
    public void setValidation(Validation validation) {
        this.validation = validation;
    }

    /**
     * Perform the validation of before invoking the actual method based on <b>validation</b> attribute value.
     * @param invoker    service
     * @param invocation invocation.
     * @return Method invocation result
     * @throws RpcException Throws RpcException if  validation failed or any other runtime exception occurred.
     */
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        if (validation != null && !invocation.getMethodName().startsWith("$")
                && ConfigUtils.isNotEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), VALIDATION_KEY))) {
            try {
                Validator validator = validation.getValidator(invoker.getUrl());
                if (validator != null) {
                    validator.validate(invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments());
                }
            } catch (RpcException e) {
                throw e;
            } catch (Throwable t) {
                return AsyncRpcResult.newDefaultAsyncResult(t, invocation);
            }
        }
        return invoker.invoke(invocation);
    }

}
  • ValidationFilter实现了Filter接口,其invoke方法在validation不为null且invoker的URL中的method参数中包含有validation,且方法名不是$开头的,那么就会从validation获取validator,然后进行校验

Validation

dubbo-2.7.2/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java

@SPI("jvalidation")
public interface Validation {

    /**
     * Return the instance of {@link Validator} for a given url.
     * @param url Invocation url
     * @return Instance of {@link Validator}
     */
    @Adaptive(VALIDATION_KEY)
    Validator getValidator(URL url);

}
  • Validation接口定义了getValidator方法

AbstractValidation

dubbo-2.7.2/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java

public abstract class AbstractValidation implements Validation {

    private final ConcurrentMap<String, Validator> validators = new ConcurrentHashMap<>();

    @Override
    public Validator getValidator(URL url) {
        String key = url.toFullString();
        Validator validator = validators.get(key);
        if (validator == null) {
            validators.put(key, createValidator(url));
            validator = validators.get(key);
        }
        return validator;
    }

    protected abstract Validator createValidator(URL url);

}
  • AbstractValidation实现了Validation接口,它定义了一个ConcurrentHashMap类型的validators,并且实现了getValidator方法,同时定义了createValidator抽象方法供子类实现

JValidation

dubbo-2.7.2/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java

public class JValidation extends AbstractValidation {

    /**
     * Return new instance of {@link JValidator}
     * @param url Valid URL instance
     * @return Instance of JValidator
     */
    @Override
    protected Validator createValidator(URL url) {
        return new JValidator(url);
    }

}
  • JValidation继承了AbstractValidation,它的createValidator创建的是JValidator

Validator

dubbo-2.7.2/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java

public interface Validator {

    void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception;

}
  • Validator接口定义了validate方法

JValidator

dubbo-2.7.2/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java

public class JValidator implements Validator {

    private static final Logger logger = LoggerFactory.getLogger(JValidator.class);

    private final Class<?> clazz;

    private final Map<String, Class> methodClassMap;

    private final javax.validation.Validator validator;

    @SuppressWarnings({"unchecked", "rawtypes"})
    public JValidator(URL url) {
        this.clazz = ReflectUtils.forName(url.getServiceInterface());
        String jvalidation = url.getParameter("jvalidation");
        ValidatorFactory factory;
        if (jvalidation != null && jvalidation.length() > 0) {
            factory = Validation.byProvider((Class) ReflectUtils.forName(jvalidation)).configure().buildValidatorFactory();
        } else {
            factory = Validation.buildDefaultValidatorFactory();
        }
        this.validator = factory.getValidator();
        this.methodClassMap = new ConcurrentHashMap<>();
    }

    //......

    @Override
    public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
        List<Class<?>> groups = new ArrayList<>();
        Class<?> methodClass = methodClass(methodName);
        if (methodClass != null) {
            groups.add(methodClass);
        }
        Set<ConstraintViolation<?>> violations = new HashSet<>();
        Method method = clazz.getMethod(methodName, parameterTypes);
        Class<?>[] methodClasses;
        if (method.isAnnotationPresent(MethodValidated.class)){
            methodClasses = method.getAnnotation(MethodValidated.class).value();
            groups.addAll(Arrays.asList(methodClasses));
        }
        // add into default group
        groups.add(0, Default.class);
        groups.add(1, clazz);

        // convert list to array
        Class<?>[] classgroups = groups.toArray(new Class[groups.size()]);

        Object parameterBean = getMethodParameterBean(clazz, method, arguments);
        if (parameterBean != null) {
            violations.addAll(validator.validate(parameterBean, classgroups ));
        }

        for (Object arg : arguments) {
            validate(violations, arg, classgroups);
        }

        if (!violations.isEmpty()) {
            logger.error("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations);
            throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations);
        }
    }

    //......
}
  • JValidator实现了Validator接口,其validate方法内部使用的是javax.validation.ValidatorFactory创建的javax.validation.Validator

实例

dubbo-2.7.2/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java

public class ValidationFilterTest {
    private Invoker<?> invoker = mock(Invoker.class);
    private Validation validation = mock(Validation.class);
    private Validator validator = mock(Validator.class);
    private RpcInvocation invocation = mock(RpcInvocation.class);

    private ValidationFilter validationFilter;

    @BeforeEach
    public void setUp() throws Exception {
        this.validationFilter = new ValidationFilter();
    }

    @Test
    public void testItWithNotExistClass() throws Exception {
        URL url = URL.valueOf("test://test:11/test?default.validation=true");

        given(validation.getValidator(url)).willThrow(new IllegalStateException("Not found class test, cause: test"));
        given(invoker.invoke(invocation)).willReturn(new AppResponse("success"));
        given(invoker.getUrl()).willReturn(url);
        given(invocation.getMethodName()).willReturn("echo1");
        given(invocation.getParameterTypes()).willReturn(new Class<?>[]{String.class});
        given(invocation.getArguments()).willReturn(new Object[]{"arg1"});

        validationFilter.setValidation(validation);
        Result result = validationFilter.invoke(invoker, invocation);

        assertThat(result.getException().getMessage(), is("Not found class test, cause: test"));

    }

    @Test
    public void testItWithExistClass() throws Exception {
        URL url = URL.valueOf("test://test:11/test?default.validation=true");

        given(validation.getValidator(url)).willReturn(validator);
        given(invoker.invoke(invocation)).willReturn(new AppResponse("success"));
        given(invoker.getUrl()).willReturn(url);
        given(invocation.getMethodName()).willReturn("echo1");
        given(invocation.getParameterTypes()).willReturn(new Class<?>[]{String.class});
        given(invocation.getArguments()).willReturn(new Object[]{"arg1"});

        validationFilter.setValidation(validation);
        Result result = validationFilter.invoke(invoker, invocation);

        assertThat(String.valueOf(result.getValue()), is("success"));
    }

    @Test
    public void testItWithoutUrlParameters() throws Exception {
        URL url = URL.valueOf("test://test:11/test");

        given(validation.getValidator(url)).willReturn(validator);
        given(invoker.invoke(invocation)).willReturn(new AppResponse("success"));
        given(invoker.getUrl()).willReturn(url);
        given(invocation.getMethodName()).willReturn("echo1");
        given(invocation.getParameterTypes()).willReturn(new Class<?>[]{String.class});
        given(invocation.getArguments()).willReturn(new Object[]{"arg1"});

        validationFilter.setValidation(validation);
        Result result = validationFilter.invoke(invoker, invocation);

        assertThat(String.valueOf(result.getValue()), is("success"));
    }

    @Test
    public void testItWhileMethodNameStartWithDollar() throws Exception {
        URL url = URL.valueOf("test://test:11/test");

        given(validation.getValidator(url)).willReturn(validator);
        given(invoker.invoke(invocation)).willReturn(new AppResponse("success"));
        given(invoker.getUrl()).willReturn(url);
        given(invocation.getMethodName()).willReturn("$echo1");
        given(invocation.getParameterTypes()).willReturn(new Class<?>[]{String.class});
        given(invocation.getArguments()).willReturn(new Object[]{"arg1"});

        validationFilter.setValidation(validation);
        Result result = validationFilter.invoke(invoker, invocation);

        assertThat(String.valueOf(result.getValue()), is("success"));

    }


    @Test
    public void testItWhileThrowoutRpcException() throws Exception {
        Assertions.assertThrows(RpcException.class, () -> {
            URL url = URL.valueOf("test://test:11/test?default.validation=true");

            given(validation.getValidator(url)).willThrow(new RpcException("rpc exception"));
            given(invoker.invoke(invocation)).willReturn(new AppResponse("success"));
            given(invoker.getUrl()).willReturn(url);
            given(invocation.getMethodName()).willReturn("echo1");
            given(invocation.getParameterTypes()).willReturn(new Class<?>[]{String.class});
            given(invocation.getArguments()).willReturn(new Object[]{"arg1"});

            validationFilter.setValidation(validation);
            validationFilter.invoke(invoker, invocation);
        });
    }
}
  • 这里分别验证了withNotExistClass、withExistClass、withoutUrlParameters、methodNameStartWithDollar、throwoutRpcException这几个场景

小结

  • ValidationFilter实现了Filter接口,其invoke方法在validation不为null且invoker的URL中的method参数中包含有validation,且方法名不是$开头的,那么就会从validation获取validator,然后进行校验
  • Validation接口定义了getValidator方法;JValidation继承了AbstractValidation,它的createValidator创建的是JValidator
  • JValidator实现了Validator接口,其validate方法内部使用的是javax.validation.ValidatorFactory创建的javax.validation.Validator

doc

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,923评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,154评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,775评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,960评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,976评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,972评论 1 295
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,893评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,709评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,159评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,400评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,552评论 1 346
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,265评论 5 341
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,876评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,528评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,701评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,552评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,451评论 2 352

推荐阅读更多精彩内容