下面列出了怎么用org.springframework.util.AntPathMatcher的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Private constructor accepting a collection of patterns.
*/
private PatternsRequestCondition(Collection<String> patterns, @Nullable UrlPathHelper urlPathHelper,
@Nullable PathMatcher pathMatcher, boolean useSuffixPatternMatch,
boolean useTrailingSlashMatch, @Nullable List<String> fileExtensions) {
this.patterns = Collections.unmodifiableSet(prependLeadingSlash(patterns));
this.pathHelper = urlPathHelper != null ? urlPathHelper : new UrlPathHelper();
this.pathMatcher = pathMatcher != null ? pathMatcher : new AntPathMatcher();
this.useSuffixPatternMatch = useSuffixPatternMatch;
this.useTrailingSlashMatch = useTrailingSlashMatch;
if (fileExtensions != null) {
for (String fileExtension : fileExtensions) {
if (fileExtension.charAt(0) != '.') {
fileExtension = "." + fileExtension;
}
this.fileExtensions.add(fileExtension);
}
}
}
/**
* Adds an alias to an existing well-known name or registers a new instance of a {@link PathMatcher}
* under that well-known name, unless already registered.
* @return a RuntimeBeanReference to this {@link PathMatcher} instance
*/
public static RuntimeBeanReference registerPathMatcher(@Nullable RuntimeBeanReference pathMatcherRef,
ParserContext parserContext, @Nullable Object source) {
if (pathMatcherRef != null) {
if (parserContext.getRegistry().isAlias(PATH_MATCHER_BEAN_NAME)) {
parserContext.getRegistry().removeAlias(PATH_MATCHER_BEAN_NAME);
}
parserContext.getRegistry().registerAlias(pathMatcherRef.getBeanName(), PATH_MATCHER_BEAN_NAME);
}
else if (!parserContext.getRegistry().isAlias(PATH_MATCHER_BEAN_NAME) &&
!parserContext.getRegistry().containsBeanDefinition(PATH_MATCHER_BEAN_NAME)) {
RootBeanDefinition pathMatcherDef = new RootBeanDefinition(AntPathMatcher.class);
pathMatcherDef.setSource(source);
pathMatcherDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
parserContext.getRegistry().registerBeanDefinition(PATH_MATCHER_BEAN_NAME, pathMatcherDef);
parserContext.registerComponent(new BeanComponentDefinition(pathMatcherDef, PATH_MATCHER_BEAN_NAME));
}
return new RuntimeBeanReference(PATH_MATCHER_BEAN_NAME);
}
private List<HandlerInterceptor> getInterceptorsForPath(String lookupPath) {
PathMatcher pathMatcher = new AntPathMatcher();
List<HandlerInterceptor> result = new ArrayList<>();
for (Object interceptor : this.registry.getInterceptors()) {
if (interceptor instanceof MappedInterceptor) {
MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;
if (mappedInterceptor.matches(lookupPath, pathMatcher)) {
result.add(mappedInterceptor.getInterceptor());
}
}
else if (interceptor instanceof HandlerInterceptor) {
result.add((HandlerInterceptor) interceptor);
}
else {
fail("Unexpected interceptor type: " + interceptor.getClass().getName());
}
}
return result;
}
@Override
public Mono<Resource> transform(ServerWebExchange serverWebExchange, Resource resource, ResourceTransformerChain resourceTransformerChain) {
final AntPathMatcher antPathMatcher = new AntPathMatcher();
try {
boolean isIndexFound = antPathMatcher.match("**/swagger-ui/**/index.html", resource.getURL().toString());
if (isIndexFound && hasDefaultTransformations()) {
String html = defaultTransformations(resource.getInputStream());
return Mono.just(new TransformedResource(resource, html.getBytes()));
}
else {
return Mono.just(resource);
}
}
catch (Exception e) {
throw new SpringDocUIException("Failed to transform Index", e);
}
}
@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
if (configAttributeMap == null) this.loadDataSource();
List<ConfigAttribute> configAttributes = new ArrayList<>();
//获取当前访问的路径
String url = ((FilterInvocation) o).getRequestUrl();
String path = URLUtil.getPath(url);
PathMatcher pathMatcher = new AntPathMatcher();
Iterator<String> iterator = configAttributeMap.keySet().iterator();
//获取访问该路径所需资源
while (iterator.hasNext()) {
String pattern = iterator.next();
if (pathMatcher.match(pattern, path)) {
configAttributes.add(configAttributeMap.get(pattern));
}
}
// 未设置操作请求权限,返回空集合
return configAttributes;
}
/**
* Private constructor accepting a collection of patterns.
*/
private PatternsRequestCondition(Collection<String> patterns, @Nullable UrlPathHelper urlPathHelper,
@Nullable PathMatcher pathMatcher, boolean useSuffixPatternMatch,
boolean useTrailingSlashMatch, @Nullable List<String> fileExtensions) {
this.patterns = Collections.unmodifiableSet(prependLeadingSlash(patterns));
this.pathHelper = (urlPathHelper != null ? urlPathHelper : new UrlPathHelper());
this.pathMatcher = (pathMatcher != null ? pathMatcher : new AntPathMatcher());
this.useSuffixPatternMatch = useSuffixPatternMatch;
this.useTrailingSlashMatch = useTrailingSlashMatch;
if (fileExtensions != null) {
for (String fileExtension : fileExtensions) {
if (fileExtension.charAt(0) != '.') {
fileExtension = "." + fileExtension;
}
this.fileExtensions.add(fileExtension);
}
}
}
/**
* Adds an alias to an existing well-known name or registers a new instance of a {@link PathMatcher}
* under that well-known name, unless already registered.
* @return a RuntimeBeanReference to this {@link PathMatcher} instance
*/
public static RuntimeBeanReference registerPathMatcher(
RuntimeBeanReference pathMatcherRef, ParserContext parserContext, Object source) {
if (pathMatcherRef != null) {
if (parserContext.getRegistry().isAlias(PATH_MATCHER_BEAN_NAME)) {
parserContext.getRegistry().removeAlias(PATH_MATCHER_BEAN_NAME);
}
parserContext.getRegistry().registerAlias(pathMatcherRef.getBeanName(), PATH_MATCHER_BEAN_NAME);
}
else if (!parserContext.getRegistry().isAlias(PATH_MATCHER_BEAN_NAME)
&& !parserContext.getRegistry().containsBeanDefinition(PATH_MATCHER_BEAN_NAME)) {
RootBeanDefinition pathMatcherDef = new RootBeanDefinition(AntPathMatcher.class);
pathMatcherDef.setSource(source);
pathMatcherDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
parserContext.getRegistry().registerBeanDefinition(PATH_MATCHER_BEAN_NAME, pathMatcherDef);
parserContext.registerComponent(new BeanComponentDefinition(pathMatcherDef, PATH_MATCHER_BEAN_NAME));
}
return new RuntimeBeanReference(PATH_MATCHER_BEAN_NAME);
}
private List<HandlerInterceptor> getInterceptorsForPath(String lookupPath) {
PathMatcher pathMatcher = new AntPathMatcher();
List<HandlerInterceptor> result = new ArrayList<HandlerInterceptor>();
for (Object interceptor : this.registry.getInterceptors()) {
if (interceptor instanceof MappedInterceptor) {
MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;
if (mappedInterceptor.matches(lookupPath, pathMatcher)) {
result.add(mappedInterceptor.getInterceptor());
}
}
else if (interceptor instanceof HandlerInterceptor) {
result.add((HandlerInterceptor) interceptor);
}
else {
fail("Unexpected interceptor type: " + interceptor.getClass().getName());
}
}
return result;
}
@Test
public void forwardingWorks() {
RouteMatcher routeMatcher = new SimpleRouteMatcher(new AntPathMatcher("."));
RouteMatcher.Route route = routeMatcher.parseRoute("myroute.foo1.bar1");
LinkedHashMap<TagKey, String> tags = new LinkedHashMap<>();
tags.put(TagKey.of(SERVICE_NAME), "{foo}");
tags.put(TagKey.of(ROUTE_ID), "22");
tags.put(TagKey.of("mycustomkey"), "{foo}-{bar}");
Forwarding fwd = (Forwarding) forwarding(routeMatcher, route,
new BigInteger("11"), "myroute.{foo}.{bar}", tags).build();
assertThat(fwd).isNotNull();
assertThat(fwd.getEnrichedTagsMetadata().getTags()).isNotEmpty()
.containsEntry(new Key(SERVICE_NAME), "foo1")
.containsEntry(new Key(ROUTE_ID), "22")
.containsEntry(new Key("mycustomkey"), "foo1-bar1");
}
public HdfsResourceLoader(Configuration config, URI uri, String user) {
this.pathMatcher = new AntPathMatcher();
this.internalFS = true;
FileSystem tempFS = null;
try {
if (uri == null) {
uri = FileSystem.getDefaultUri(config);
}
tempFS = user != null ? FileSystem.get(uri, config, user) : FileSystem.get(uri, config);
} catch (Exception var9) {
tempFS = null;
throw new IllegalStateException("Cannot create filesystem", var9);
} finally {
this.fs = tempFS;
}
}
@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
if (configAttributeMap == null) this.loadDataSource();
List<ConfigAttribute> configAttributes = new ArrayList<>();
//获取当前访问的路径
String url = ((FilterInvocation) o).getRequestUrl();
String path = URLUtil.getPath(url);
PathMatcher pathMatcher = new AntPathMatcher();
Iterator<String> iterator = configAttributeMap.keySet().iterator();
//获取访问该路径所需资源
while (iterator.hasNext()) {
String pattern = iterator.next();
if (pathMatcher.match(pattern, path)) {
configAttributes.add(configAttributeMap.get(pattern));
}
}
// 未设置操作请求权限,返回空集合
return configAttributes;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain);
//OPTIONS请求直接放行
if(request.getMethod().equals(HttpMethod.OPTIONS.toString())){
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
return;
}
//白名单请求直接放行
PathMatcher pathMatcher = new AntPathMatcher();
for (String path : ignoreUrlsConfig.getUrls()) {
if(pathMatcher.match(path,request.getRequestURI())){
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
return;
}
}
//此处会调用AccessDecisionManager中的decide方法进行鉴权操作
InterceptorStatusToken token = super.beforeInvocation(fi);
try {
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
} finally {
super.afterInvocation(token, null);
}
}
@Override
public List<Log> getLogs() throws IOException {
final PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
resolver.setPathMatcher(new AntPathMatcher());
final Resource[] resources = resolver.getResources("file:" + getPattern());
final ArrayList<Log> logs = new ArrayList<Log>(resources.length);
// TODO Decouple direct file log association
for (int i = 0; i < resources.length; i++) {
if (resources[i].exists()) {
if (resources[i].getFile().isFile()) {
logs.add(new FileLog(resources[i].getFile()));
}
} else {
logger.info("Ignore not existent file: {}", resources[i].getFile());
}
}
return logs;
}
/**
* Private constructor accepting a collection of patterns.
*/
private PatternsRequestCondition(Collection<String> patterns, UrlPathHelper urlPathHelper,
PathMatcher pathMatcher, boolean useSuffixPatternMatch, boolean useTrailingSlashMatch,
List<String> fileExtensions) {
this.patterns = Collections.unmodifiableSet(prependLeadingSlash(patterns));
this.pathHelper = (urlPathHelper != null ? urlPathHelper : new UrlPathHelper());
this.pathMatcher = (pathMatcher != null ? pathMatcher : new AntPathMatcher());
this.useSuffixPatternMatch = useSuffixPatternMatch;
this.useTrailingSlashMatch = useTrailingSlashMatch;
if (fileExtensions != null) {
for (String fileExtension : fileExtensions) {
if (fileExtension.charAt(0) != '.') {
fileExtension = "." + fileExtension;
}
this.fileExtensions.add(fileExtension);
}
}
}
@Override
public RestfulMock findActiveByMethodAndPathPatternAndTypesForSingleUser(final RestMethodEnum method, final String path, final List<RestMockTypeEnum> mockTypes) {
final String part1 = StringUtils.split(path, AntPathMatcher.DEFAULT_PATH_SEPARATOR)[0];
final List<RestfulMock> mocks = entityManager.createQuery("FROM RestfulMock rm "
+ " WHERE rm.method = :method "
+ " AND rm.mockType IN (:mockTypes) "
+ " AND (rm.path = :path1 OR rm.path LIKE '/'||:path2||'%')"
+ " AND rm.createdBy.role = :role "
+ " AND rm.status = 'ACTIVE'", RestfulMock.class)
.setParameter("method", method)
.setParameter("mockTypes", mockTypes)
.setParameter("path1", path)
.setParameter("path2", part1)
.setParameter("role", SmockinUserRoleEnum.SYS_ADMIN)
.getResultList();
return matchPath(mocks, path, false);
}
private boolean isBranchIncluded(String branchName) {
AntPathMatcher matcher = new AntPathMatcher();
for (String includePattern : includedBranches) {
if (matcher.match(includePattern, branchName)) {
return true;
}
}
return includedBranches.isEmpty();
}
/**
* Return true if pass permissions, otherwise return false
* @param url
* @param method
* @param permissions
* @return
*/
private boolean checkPermission(String url, String method, List<Permission> permissions) {
AntPathMatcher matcher = new AntPathMatcher();
List<Permission> left = permissions.stream().filter(
(Permission p) -> matcher.match(p.getUrl(), url) && method.equals(p.getMethod())
).collect(Collectors.toList());
return !left.isEmpty();
}
private void initMatcher(String id) {
BusProperties properties = new BusProperties();
properties.setId(id);
DefaultBusPathMatcher pathMatcher = new DefaultBusPathMatcher(
new AntPathMatcher(":"));
this.matcher = new ServiceMatcher(pathMatcher, properties.getId());
}
@Override
protected void configureMessageBroker(MessageBrokerRegistry registry) {
registry.configureBrokerChannel().interceptors(this.interceptor, this.interceptor, this.interceptor);
registry.configureBrokerChannel().taskExecutor()
.corePoolSize(31).maxPoolSize(32).keepAliveSeconds(33).queueCapacity(34);
registry.setPathMatcher(new AntPathMatcher(".")).enableSimpleBroker("/topic", "/queue");
registry.setCacheLimit(8192);
registry.setPreservePublishOrder(true);
registry.setUserRegistryOrder(99);
}
@Test
public void defaultPathMatchConfiguration() throws Exception {
ApplicationContext context = initContext(WebConfig.class);
UrlPathHelper urlPathHelper = context.getBean(UrlPathHelper.class);
PathMatcher pathMatcher = context.getBean(PathMatcher.class);
assertNotNull(urlPathHelper);
assertNotNull(pathMatcher);
assertEquals(AntPathMatcher.class, pathMatcher.getClass());
}
/**
* Return a global {@link PathMatcher} instance for path matching
* patterns in {@link HandlerMapping}s.
* This instance can be configured using the {@link PathMatchConfigurer}
* in {@link #configurePathMatch(PathMatchConfigurer)}.
* @since 4.1
*/
@Bean
public PathMatcher mvcPathMatcher() {
if (getPathMatchConfigurer().getPathMatcher() != null) {
return getPathMatchConfigurer().getPathMatcher();
}
else {
return new AntPathMatcher();
}
}
@Override
public Resource transform(HttpServletRequest request, Resource resource,
ResourceTransformerChain transformerChain) throws IOException {
final AntPathMatcher antPathMatcher = new AntPathMatcher();
boolean isIndexFound = antPathMatcher.match("**/swagger-ui/**/index.html", resource.getURL().toString());
if (isIndexFound && hasDefaultTransformations()) {
String html = defaultTransformations(resource.getInputStream());
return new TransformedResource(resource, html.getBytes());
}
else
return resource;
}
/**
* 根据请求地址获取正则
* @param url
* @return
*/
private String getRegexpUrl(String url) {
List<String> list = sysPermissionService.queryPermissionUrlWithStar();
if(list!=null && list.size()>0) {
for (String p : list) {
PathMatcher matcher = new AntPathMatcher();
if(matcher.match(p, url)) {
return p;
}
}
}
return null;
}
private boolean isBranchNotExcluded(String branchName) {
AntPathMatcher matcher = new AntPathMatcher();
for (String excludePattern : excludedBranches) {
if (matcher.match(excludePattern, branchName)) {
return false;
}
}
return true;
}
/**
* 获取指定驱动器, 某个文件的直链, 然后重定向过去.
* @param driveId
* 驱动器 ID
*
* @return 重定向至文件直链
*/
@GetMapping("/directlink/{driveId}/**")
public String directlink(@PathVariable("driveId") Integer driveId, final HttpServletRequest request) {
String path = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
AntPathMatcher apm = new AntPathMatcher();
String filePath = apm.extractPathWithinPattern(bestMatchPattern, path);
if (filePath.length() > 0 && filePath.charAt(0) != ZFileConstant.PATH_SEPARATOR_CHAR) {
filePath = "/" + filePath;
}
AbstractBaseFileService fileService = driveContext.get(driveId);
FileItemDTO fileItem = fileService.getFileItem(filePath);
String url = fileItem.getUrl();
int queryIndex = url.indexOf('?');
if (queryIndex != -1) {
String origin = url.substring(0, queryIndex);
String queryString = url.substring(queryIndex + 1);
url = URLUtil.encode(origin) + "?" + URLUtil.encode(queryString);
} else {
url = URLUtil.encode(url);
}
if (Objects.equals(fileItem.getType(), FileTypeEnum.FOLDER)) {
return "redirect:" + fileItem.getUrl();
} else {
return "redirect:" + url;
}
}
private void initMatcher(String id, String[] configNames) {
BusProperties properties = new BusProperties();
properties.setId(id);
DefaultBusPathMatcher pathMatcher = new DefaultBusPathMatcher(
new AntPathMatcher(":"));
this.matcher = new ServiceMatcher(pathMatcher, properties.getId(), configNames);
}
@Override
protected void configureMessageBroker(MessageBrokerRegistry registry) {
registry.configureBrokerChannel().interceptors(this.interceptor, this.interceptor, this.interceptor);
registry.configureBrokerChannel().taskExecutor()
.corePoolSize(31).maxPoolSize(32).keepAliveSeconds(33).queueCapacity(34);
registry.setPathMatcher(new AntPathMatcher(".")).enableSimpleBroker("/topic", "/queue");
registry.setCacheLimit(8192);
registry.setPreservePublishOrder(true);
registry.setUserRegistryOrder(99);
}
public static Map<String, String> resolvePathVariables(String pathPattern, String actualPath) {
PathMatcher pathMatcher = new AntPathMatcher();
if (pathMatcher.match(pathPattern, actualPath)) {
return pathMatcher.extractUriTemplateVariables(pathPattern, actualPath);
} else {
return emptyMap();
}
}
/**
* Get the remaining path from a given request. e.g. if the request went to a method with the matching pattern of
* /api/v3/jobs/{id}/output/** and the request was /api/v3/jobs/{id}/output/blah.txt the return value of this
* method would be blah.txt.
*
* @param request The http servlet request.
* @return The remaining path
*/
public static String getRemainingPath(final HttpServletRequest request) {
String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
if (path != null) {
final String bestMatchPattern
= (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
log.debug("bestMatchPattern = {}", bestMatchPattern);
path = new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
}
path = path == null ? EMPTY_STRING : path;
log.debug("Remaining path = {}", path);
return path;
}
@Test
public void defaultPathMatchConfiguration() throws Exception {
ApplicationContext context = initContext(WebConfig.class);
UrlPathHelper urlPathHelper = context.getBean(UrlPathHelper.class);
PathMatcher pathMatcher = context.getBean(PathMatcher.class);
assertNotNull(urlPathHelper);
assertNotNull(pathMatcher);
assertEquals(AntPathMatcher.class, pathMatcher.getClass());
}