AntPathRequestMatcher.java 1.64 KB
package com.diligrp.cashier.shared.http;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpMethod;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UrlPathHelper;

public class AntPathRequestMatcher implements HttpRequestMatcher {

    private final String pattern;

    private final HttpMethod httpMethod;

    private final PathMatcher matcher;

    private final UrlPathHelper urlPathHelper;

    public AntPathRequestMatcher(String pattern, HttpMethod httpMethod, boolean caseSensitive) {
        Assert.hasText(pattern, "Pattern cannot be null or empty");
        this.pattern = pattern;
        this.httpMethod = httpMethod;
        this.matcher = createPathMatcher(caseSensitive);
        this.urlPathHelper = new UrlPathHelper();
    }

    @Override
    public boolean matches(HttpServletRequest request) {
        if (this.httpMethod != null && StringUtils.hasText(request.getMethod()) &&
            this.httpMethod != HttpMethod.valueOf(request.getMethod())) {
            return false;
        }
        if (this.pattern.equals("/**")) {
            return true;
        }

        String url = this.urlPathHelper.getPathWithinApplication(request);
        return this.matcher.match(this.pattern, url);
    }

    private PathMatcher createPathMatcher(boolean caseSensitive) {
        AntPathMatcher pathMatcher = new AntPathMatcher();
        pathMatcher.setTrimTokens(false);
        pathMatcher.setCaseSensitive(caseSensitive);
        return pathMatcher;
    }
}