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

cc.shacocloud.mirage.web.HandlerInterceptorComposite Maven / Gradle / Ivy

package cc.shacocloud.mirage.web;

import cc.shacocloud.mirage.utils.SelfSortBanRepeatedList;
import cc.shacocloud.mirage.web.util.PathUtil;
import lombok.Setter;
import org.jetbrains.annotations.Nullable;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import java.util.ArrayList;
import java.util.List;

/**
 * 拦截处理器聚合对象,通 {@link #match} 方法匹配合适的拦截器集合,然后委派给 {@link HandlerInterceptor} 处理
 */
public class HandlerInterceptorComposite {

    private final List interceptorMappings = new SelfSortBanRepeatedList<>(InterceptorMappingInfo::getOrder, InterceptorMappingInfo::getInterceptorName);

    /**
     * 路径匹配器
     */
    @Setter
    private PathMatcher pathMatcher = new AntPathMatcher();

    /**
     * 返回与指定路径相匹配的拦截器集合,拦截器集合使用 {@link AnnotationAwareOrderComparator#sort(List)} 排序
     *
     * @param paths 带匹配的路径
     * @return 匹配的拦截器集合
     */
    @Nullable
    public List match(String... paths) {
        if (paths == null || paths.length == 0) return null;

        List interceptors = new ArrayList<>();

        for (InterceptorMappingInfo interceptorInfo : this.interceptorMappings) {
            String[] excludePatterns = interceptorInfo.getExcludePatterns();
            String[] includePatterns = interceptorInfo.getIncludePatterns();
            boolean matches = PathUtil.matches(paths, pathMatcher, excludePatterns, includePatterns);
            if (matches) {
                interceptors.add(interceptorInfo.getHandler());
            }
        }

        if (interceptors.isEmpty()) return null;

        AnnotationAwareOrderComparator.sort(interceptors);
        return interceptors;
    }


    /**
     * 添加拦截器映射
     *
     * @param interceptorMappingInfo 拦截器映射信息
     */
    public void addInterceptor(InterceptorMappingInfo interceptorMappingInfo) {
        this.interceptorMappings.add(interceptorMappingInfo);
    }

    /**
     * 添加拦截器映射
     *
     * @param interceptorMappingInfos 拦截器映射信息
     */
    public void addInterceptor(List interceptorMappingInfos) {
        this.interceptorMappings.addAll(interceptorMappingInfos);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy