Encode.java 2.59 KB
package com.topdraw.dockingapi.config;

import com.alibaba.fastjson.JSON;
import com.dtflys.forest.annotation.MethodLifeCycle;
import com.dtflys.forest.annotation.RequestAttributes;
import com.dtflys.forest.http.ForestBody;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.lifecycles.MethodAnnotationLifeCycle;
import com.dtflys.forest.reflection.ForestMethod;
import com.topdraw.dockingapi.entity.EncryptEntity;
import com.topdraw.dockingapi.util.DecryptUtils;
import lombok.SneakyThrows;

import java.lang.annotation.*;
import java.lang.reflect.Parameter;

/**
 * 用Forest自定义注解实现一个自定义的签名加密注解
 * 凡用此接口修饰的方法或接口,其对应的所有请求都会执行自定义的签名加密过程
 * 而自定义的签名加密过程,由这里的@MethodLifeCycle注解指定的生命周期类进行处理
 * 可以将此注解用在接口类和方法上
 */
@Documented
@MethodLifeCycle(Encode.EncodeLifeCycle.class)
@RequestAttributes
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
public @interface Encode {

    String value() default "";


    class EncodeLifeCycle implements MethodAnnotationLifeCycle<Encode, Object> {


        /**
         * 当方法调用时调用此方法,此时还没有执行请求发送
         * 此方法可以获得请求对应的方法调用信息,以及动态传入的方法调用参数列表
         */
        @SneakyThrows
        @Override
        public void onInvokeMethod(ForestRequest request, ForestMethod method, Object[] args) {
            String value = (String) getAttribute(request, "value");
            for (Object arg : args) {
                Parameter[] parameters = method.getMethod().getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    Encode annotation = parameters[i].getAnnotation(Encode.class);
                    if (annotation != null) {
                        Object body = args[i];
                        String jsonString = JSON.toJSONString(body);
                        String encode = DecryptUtils.encode(value, jsonString);
                        EncryptEntity encodeBody = new EncryptEntity(encode);
                        ForestBody forestBody = request.getBody();
                        //替换body
                        forestBody.clear();
                        request.addBody(encodeBody);
                    }
                }
            }
        }


        @Override
        public void onMethodInitialized(ForestMethod method, Encode annotation) {

        }
    }


}