下面列出了怎么用org.springframework.util.PatternMatchUtils的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 判断接口是否有xxx:xxx权限
*
* @param permission 权限
* @return {boolean}
*/
public boolean hasPermission(String permission) {
if (StrUtil.isBlank(permission)) {
return false;
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
return false;
}
return authentication
.getAuthorities()
.stream()
.map(GrantedAuthority::getAuthority)
.filter(StringUtils::hasText)
.anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x));
}
/**
* Find image by its name, or id
* @param name
* @param imageId
* @return
*/
public Image findImage(String name, String imageId) {
Image res = null;
if(imageId != null) {
res = imagesByName.get(imageId);
}
String withoutTag = ImageName.withoutTagOrNull(name);
if(res == null && withoutTag != null) {
res = imagesByName.get(withoutTag);
}
if(res == null && (imageId != null || withoutTag != null)) {
for(Image img: imagesWithPattern) {
String pattern = img.getName();
if(withoutTag != null && PatternMatchUtils.simpleMatch(pattern, withoutTag) ||
imageId != null && PatternMatchUtils.simpleMatch(pattern, imageId)) {
res = img;
break;
}
}
}
return res;
}
@Override
public void doFilter ( ServletRequest request , ServletResponse response , FilterChain chain )
throws IOException, ServletException {
if ( PatternMatchUtils.simpleMatch( excludeUrlPatterns , ( ( HttpServletRequest ) request ).getRequestURI() ) ) {
chain.doFilter( request , response );
return;
}
final BodyReaderWrapper wrapper = new BodyReaderWrapper( ( HttpServletRequest ) request );
String requestMessage = RequestUtils.getRequestMessage( wrapper );
if ( ! LogUtils.getLogger().isDebugEnabled() ) {
requestMessage = StringUtils.replaceAll( requestMessage , PASSWORD_FILTER_REGEX ,
"enable password protection, if not debug so do not see"
);
}
LogUtils.getLogger().info( requestMessage );
chain.doFilter( wrapper , response );
}
private ZuulWebSocketProperties.WsBrokerage getWebSocketBrokarage(URI uri) {
String path = uri.toString();
if (path.contains(":")) {
path = UriComponentsBuilder.fromUriString(path).build().getPath();
}
for (Map.Entry<String, ZuulWebSocketProperties.WsBrokerage> entry : zuulWebSocketProperties
.getBrokerages().entrySet()) {
ZuulWebSocketProperties.WsBrokerage wsBrokerage = entry.getValue();
if (wsBrokerage.isEnabled()) {
for (String endPoint : wsBrokerage.getEndPoints()) {
if (PatternMatchUtils.simpleMatch(toPattern(endPoint), path + "/")) {
return wsBrokerage;
}
}
}
}
return null;
}
/**
* 扫描目录下的文件
*
* @param path 路径
* @param fileNamePattern 文件名 * 号
* @return 文件集合
*/
public static List<File> list(String path, final String fileNamePattern) {
File file = new File(path);
return list(file, pathname -> {
String fileName = pathname.getName();
return PatternMatchUtils.simpleMatch(fileNamePattern, fileName);
});
}
/**
* 扫描目录下的文件
*
* @param file 文件
* @param fileNamePattern "xxx*", "*xxx", "*xxx*" and "xxx*yyy"
* @return 文件集合
*/
public static List<File> list(File file, final String fileNamePattern) {
List<File> fileList = new ArrayList<>();
return list(file, fileList, pathname -> {
String fileName = pathname.getName();
return PatternMatchUtils.simpleMatch(fileNamePattern, fileName);
});
}
/**
* 扫描目录下的文件
*
* @param file 文件
* @param fileNamePatterns "xxx*", "*xxx", "*xxx*" and "xxx*yyy"
* @return 文件集合
*/
public static List<File> list(File file, final String... fileNamePatterns) {
List<File> fileList = new ArrayList<>();
return list(file, fileList, pathname -> {
String fileName = pathname.getName();
return PatternMatchUtils.simpleMatch(fileNamePatterns, fileName);
});
}
/**
* 判断接口是否有xxx:xxx权限
*
* @param permission 权限
* @return {boolean}
*/
public boolean hasPermission(String permission) {
if (StrUtil.isBlank(permission)) {
return false;
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
return false;
}
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
return authorities.stream()
.map(GrantedAuthority::getAuthority)
.filter(StringUtils::hasText)
.anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x));
}
private List<String> getMatchingHeaderNames(String pattern, @Nullable Map<String, Object> headers) {
if (headers == null) {
return Collections.emptyList();
}
List<String> matchingHeaderNames = new ArrayList<>();
for (String key : headers.keySet()) {
if (PatternMatchUtils.simpleMatch(pattern, key)) {
matchingHeaderNames.add(key);
}
}
return matchingHeaderNames;
}
/**
* Apply further settings to the given bean definition,
* beyond the contents retrieved from scanning the component class.
* @param beanDefinition the scanned bean definition
* @param beanName the generated bean name for the given bean
*/
protected void postProcessBeanDefinition(AbstractBeanDefinition beanDefinition, String beanName) {
beanDefinition.applyDefaults(this.beanDefinitionDefaults);
if (this.autowireCandidatePatterns != null) {
beanDefinition.setAutowireCandidate(PatternMatchUtils.simpleMatch(this.autowireCandidatePatterns, beanName));
}
}
/**
* Return the {@link SQLErrorCodes} instance for the given database.
* <p>No need for a database meta-data lookup.
* @param databaseName the database name (must not be {@code null})
* @return the {@code SQLErrorCodes} instance for the given database
* @throws IllegalArgumentException if the supplied database name is {@code null}
*/
public SQLErrorCodes getErrorCodes(String databaseName) {
Assert.notNull(databaseName, "Database product name must not be null");
SQLErrorCodes sec = this.errorCodesMap.get(databaseName);
if (sec == null) {
for (SQLErrorCodes candidate : this.errorCodesMap.values()) {
if (PatternMatchUtils.simpleMatch(candidate.getDatabaseProductNames(), databaseName)) {
sec = candidate;
break;
}
}
}
if (sec != null) {
checkCustomTranslatorRegistry(databaseName, sec);
if (logger.isDebugEnabled()) {
logger.debug("SQL error codes for '" + databaseName + "' found");
}
return sec;
}
// Could not find the database among the defined ones.
if (logger.isDebugEnabled()) {
logger.debug("SQL error codes for '" + databaseName + "' not found");
}
return new SQLErrorCodes();
}
@Override
public boolean shouldFilter() {
RequestContext requestContext = RequestContext.getCurrentContext();
HttpServletRequest request = requestContext.getRequest();
return PatternMatchUtils.simpleMatch("*-anon/internal*", request.getRequestURI());
}
/**
* 拥有任意权限均可访问
*
* @param permissions 权限标识列表
* @return 满足其中一个权限,返回 true,反之 false
*/
public boolean hasAnyPermission(String... permissions) {
SecureUser currentUser = secureUtil.getCurrentUser();
if (currentUser == null) {
return false;
}
// 使用 PatternMatchUtils 支持 * 号
return currentUser.getPermissions().stream().anyMatch(x -> PatternMatchUtils.simpleMatch(permissions, x));
}
private List<String> getMatchingHeaderNames(String pattern, @Nullable Map<String, Object> headers) {
List<String> matchingHeaderNames = new ArrayList<>();
if (headers != null) {
for (String key : headers.keySet()) {
if (PatternMatchUtils.simpleMatch(pattern, key)) {
matchingHeaderNames.add(key);
}
}
}
return matchingHeaderNames;
}
/**
* Apply further settings to the given bean definition,
* beyond the contents retrieved from scanning the component class.
* @param beanDefinition the scanned bean definition
* @param beanName the generated bean name for the given bean
*/
protected void postProcessBeanDefinition(AbstractBeanDefinition beanDefinition, String beanName) {
beanDefinition.applyDefaults(this.beanDefinitionDefaults);
if (this.autowireCandidatePatterns != null) {
beanDefinition.setAutowireCandidate(PatternMatchUtils.simpleMatch(this.autowireCandidatePatterns, beanName));
}
}
/**
* Return the {@link SQLErrorCodes} instance for the given database.
* <p>No need for a database meta-data lookup.
* @param databaseName the database name (must not be {@code null})
* @return the {@code SQLErrorCodes} instance for the given database
* @throws IllegalArgumentException if the supplied database name is {@code null}
*/
public SQLErrorCodes getErrorCodes(String databaseName) {
Assert.notNull(databaseName, "Database product name must not be null");
SQLErrorCodes sec = this.errorCodesMap.get(databaseName);
if (sec == null) {
for (SQLErrorCodes candidate : this.errorCodesMap.values()) {
if (PatternMatchUtils.simpleMatch(candidate.getDatabaseProductNames(), databaseName)) {
sec = candidate;
break;
}
}
}
if (sec != null) {
checkCustomTranslatorRegistry(databaseName, sec);
if (logger.isDebugEnabled()) {
logger.debug("SQL error codes for '" + databaseName + "' found");
}
return sec;
}
// Could not find the database among the defined ones.
if (logger.isDebugEnabled()) {
logger.debug("SQL error codes for '" + databaseName + "' not found");
}
return new SQLErrorCodes();
}
@Nullable
public static HttpHeaders toHeaders(
@Nullable BladeHystrixAccountGetter accountGetter,
BladeHystrixHeadersProperties properties) {
HttpServletRequest request = WebUtil.getRequest();
if (request == null) {
return null;
}
HttpHeaders headers = new HttpHeaders();
String accountHeaderName = properties.getAccount();
// 如果配置有 account 读取器
if (accountGetter != null) {
String xAccountHeader = accountGetter.get(request);
if (StringUtil.isNotBlank(xAccountHeader)) {
headers.add(accountHeaderName, xAccountHeader);
}
}
List<String> allowHeadsList = new ArrayList<>(Arrays.asList(ALLOW_HEADS));
// 如果有传递 account header 继续往下层传递
allowHeadsList.add(accountHeaderName);
// 传递请求头
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
List<String> allowed = properties.getAllowed();
String pattern = properties.getPattern();
while (headerNames.hasMoreElements()) {
String key = headerNames.nextElement();
// 只支持配置的 header
if (allowHeadsList.contains(key) || allowed.contains(key) || PatternMatchUtils.simpleMatch(pattern, key)) {
String values = request.getHeader(key);
// header value 不为空的 传递
if (StringUtil.isNotBlank(values)) {
headers.add(key, values);
}
}
}
}
return headers.isEmpty() ? null : headers;
}
/**
* 扫描目录下的文件
*
* @param path 路径
* @param fileNamePattern 文件名 * 号
* @return 文件集合
*/
public static List<File> list(String path, final String fileNamePattern) {
File file = new File(path);
return list(file, pathname -> {
String fileName = pathname.getName();
return PatternMatchUtils.simpleMatch(fileNamePattern, fileName);
});
}
/**
* 扫描目录下的文件
*
* @param file 文件
* @param fileNamePattern Spring AntPathMatcher 规则
* @return 文件集合
*/
public static List<File> list(File file, final String fileNamePattern) {
List<File> fileList = new ArrayList<>();
return list(file, fileList, pathname -> {
String fileName = pathname.getName();
return PatternMatchUtils.simpleMatch(fileNamePattern, fileName);
});
}
/**
* 判断接口是否有xxx:xxx权限
*
* @param permission 权限
* @return {boolean}
*/
public boolean hasPermission(String permission) {
if (StrUtil.isBlank(permission)) {
return false;
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
return false;
}
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
return authorities.stream()
.map(GrantedAuthority::getAuthority)
.filter(StringUtils::hasText)
.anyMatch(x -> PatternMatchUtils.simpleMatch(permission, x));
}
@Override
protected boolean innerTest(CharSequence text) {
if(text == null) {
//obviously that '*' math null strings too
return "*".equals(pattern);
}
return PatternMatchUtils.simpleMatch(pattern, text.toString());
}
/**
* Return the {@link SQLErrorCodes} instance for the given database.
* <p>No need for a database metadata lookup.
* @param databaseName the database name (must not be {@code null})
* @return the {@code SQLErrorCodes} instance for the given database
* @throws IllegalArgumentException if the supplied database name is {@code null}
*/
public SQLErrorCodes getErrorCodes(String databaseName) {
Assert.notNull(databaseName, "Database product name must not be null");
SQLErrorCodes sec = this.errorCodesMap.get(databaseName);
if (sec == null) {
for (SQLErrorCodes candidate : this.errorCodesMap.values()) {
if (PatternMatchUtils.simpleMatch(candidate.getDatabaseProductNames(), databaseName)) {
sec = candidate;
break;
}
}
}
if (sec != null) {
checkCustomTranslatorRegistry(databaseName, sec);
if (logger.isDebugEnabled()) {
logger.debug("SQL error codes for '" + databaseName + "' found");
}
return sec;
}
// Could not find the database among the defined ones.
if (logger.isDebugEnabled()) {
logger.debug("SQL error codes for '" + databaseName + "' not found");
}
return new SQLErrorCodes();
}
/**
* Apply further settings to the given bean definition,
* beyond the contents retrieved from scanning the component class.
* @param beanDefinition the scanned bean definition
* @param beanName the generated bean name for the given bean
*/
protected void postProcessBeanDefinition(AbstractBeanDefinition beanDefinition, String beanName) {
beanDefinition.applyDefaults(this.beanDefinitionDefaults);
if (this.autowireCandidatePatterns != null) {
beanDefinition.setAutowireCandidate(PatternMatchUtils.simpleMatch(this.autowireCandidatePatterns, beanName));
}
}
private String getWebSocketServerPath(ZuulWebSocketProperties.WsBrokerage wsBrokerage,
URI uri) {
String path = uri.toString();
if (path.contains(":")) {
path = UriComponentsBuilder.fromUriString(path).build().getPath();
}
for (String endPoint : wsBrokerage.getEndPoints()) {
if (PatternMatchUtils.simpleMatch(toPattern(endPoint), path + "/")) {
return endPoint;
}
}
return null;
}
private List<String> getMatchingHeaderNames(String pattern, Map<String, Object> headers) {
List<String> matchingHeaderNames = new ArrayList<String>();
if (headers != null) {
for (String key : headers.keySet()) {
if (PatternMatchUtils.simpleMatch(pattern, key)) {
matchingHeaderNames.add(key);
}
}
}
return matchingHeaderNames;
}
/**
* Apply further settings to the given bean definition,
* beyond the contents retrieved from scanning the component class.
* @param beanDefinition the scanned bean definition
* @param beanName the generated bean name for the given bean
*/
protected void postProcessBeanDefinition(AbstractBeanDefinition beanDefinition, String beanName) {
beanDefinition.applyDefaults(this.beanDefinitionDefaults);
if (this.autowireCandidatePatterns != null) {
beanDefinition.setAutowireCandidate(PatternMatchUtils.simpleMatch(this.autowireCandidatePatterns, beanName));
}
}
/**
* Return the {@link SQLErrorCodes} instance for the given database.
* <p>No need for a database metadata lookup.
* @param dbName the database name (must not be {@code null})
* @return the {@code SQLErrorCodes} instance for the given database
* @throws IllegalArgumentException if the supplied database name is {@code null}
*/
public SQLErrorCodes getErrorCodes(String dbName) {
Assert.notNull(dbName, "Database product name must not be null");
SQLErrorCodes sec = this.errorCodesMap.get(dbName);
if (sec == null) {
for (SQLErrorCodes candidate : this.errorCodesMap.values()) {
if (PatternMatchUtils.simpleMatch(candidate.getDatabaseProductNames(), dbName)) {
sec = candidate;
break;
}
}
}
if (sec != null) {
checkCustomTranslatorRegistry(dbName, sec);
if (logger.isDebugEnabled()) {
logger.debug("SQL error codes for '" + dbName + "' found");
}
return sec;
}
// Could not find the database among the defined ones.
if (logger.isDebugEnabled()) {
logger.debug("SQL error codes for '" + dbName + "' not found");
}
return new SQLErrorCodes();
}
private static boolean match(String pattern, String image, String imageId) {
if(isAll(pattern)) {
return true;
}
boolean isPattern = isPattern(pattern);
if(ImageName.isId(image) && !isPattern) {
return pattern.equals(imageId == null? image : imageId);
}
String imageVersion = ContainerUtils.getImageVersion(image);
if(isPattern) {
return PatternMatchUtils.simpleMatch(pattern, imageVersion);
} else {
return pattern.equals(imageVersion);
}
}
/**
* Apply the attributes of the given bean element to the given bean * definition.
* @param ele bean declaration element
* @param beanName bean name
* @param containingBean containing bean definition
* @return a bean definition initialized according to the bean element attributes
*/
public AbstractBeanDefinition parseBeanDefinitionAttributes(Element ele, String beanName,
@Nullable BeanDefinition containingBean, AbstractBeanDefinition bd) {
// 注释 2.5 老版本 1.x 用的是 singleton 属性,应该升级使用 scope 属性,报错
if (ele.hasAttribute(SINGLETON_ATTRIBUTE)) {
error("Old 1.x 'singleton' attribute in use - upgrade to 'scope' declaration", ele);
}
// 解析 scope 领域属性
else if (ele.hasAttribute(SCOPE_ATTRIBUTE)) {
bd.setScope(ele.getAttribute(SCOPE_ATTRIBUTE));
}
else if (containingBean != null) {
// Take default from containing bean in case of an inner bean definition.
// 在嵌入 beanDefinition 情况,并且没有单独指定 scope 属性,将会使用父类默认的属性
bd.setScope(containingBean.getScope());
}
// 解析 abstract 属性
if (ele.hasAttribute(ABSTRACT_ATTRIBUTE)) {
bd.setAbstract(TRUE_VALUE.equals(ele.getAttribute(ABSTRACT_ATTRIBUTE)));
}
// 是否延迟初始化,就是在第一次被调用时才进行实例化
String lazyInit = ele.getAttribute(LAZY_INIT_ATTRIBUTE);
if (isDefaultValue(lazyInit)) {
lazyInit = this.defaults.getLazyInit();
}
bd.setLazyInit(TRUE_VALUE.equals(lazyInit));
// 解析 autowire 属性
String autowire = ele.getAttribute(AUTOWIRE_ATTRIBUTE);
bd.setAutowireMode(getAutowireMode(autowire));
// 解析 depends-on 属性
if (ele.hasAttribute(DEPENDS_ON_ATTRIBUTE)) {
String dependsOn = ele.getAttribute(DEPENDS_ON_ATTRIBUTE);
bd.setDependsOn(StringUtils.tokenizeToStringArray(dependsOn, MULTI_VALUE_ATTRIBUTE_DELIMITERS));
}
// 解析 autowire-candidate 属性
String autowireCandidate = ele.getAttribute(AUTOWIRE_CANDIDATE_ATTRIBUTE);
if (isDefaultValue(autowireCandidate)) {
String candidatePattern = this.defaults.getAutowireCandidates();
if (candidatePattern != null) {
String[] patterns = StringUtils.commaDelimitedListToStringArray(candidatePattern);
bd.setAutowireCandidate(PatternMatchUtils.simpleMatch(patterns, beanName));
}
}
else {
bd.setAutowireCandidate(TRUE_VALUE.equals(autowireCandidate));
}
// 解析 primary 属性
if (ele.hasAttribute(PRIMARY_ATTRIBUTE)) {
bd.setPrimary(TRUE_VALUE.equals(ele.getAttribute(PRIMARY_ATTRIBUTE)));
}
// 解析 init-method 属性(这个方法,在初始化时会被调用~)
if (ele.hasAttribute(INIT_METHOD_ATTRIBUTE)) {
String initMethodName = ele.getAttribute(INIT_METHOD_ATTRIBUTE);
bd.setInitMethodName(initMethodName);
}
// 如果用户没有设置初始化方法,而加载类有默认初始化方法,设置默认
else if (this.defaults.getInitMethod() != null) {
bd.setInitMethodName(this.defaults.getInitMethod());
bd.setEnforceInitMethod(false);
}
// 解析 destroy-method 属性
if (ele.hasAttribute(DESTROY_METHOD_ATTRIBUTE)) {
String destroyMethodName = ele.getAttribute(DESTROY_METHOD_ATTRIBUTE);
bd.setDestroyMethodName(destroyMethodName);
}
else if (this.defaults.getDestroyMethod() != null) {
bd.setDestroyMethodName(this.defaults.getDestroyMethod());
bd.setEnforceDestroyMethod(false);
}
// 解析 factory-method 属性
if (ele.hasAttribute(FACTORY_METHOD_ATTRIBUTE)) {
bd.setFactoryMethodName(ele.getAttribute(FACTORY_METHOD_ATTRIBUTE));
}
// 解析 factory-bean 属性
if (ele.hasAttribute(FACTORY_BEAN_ATTRIBUTE)) {
bd.setFactoryBeanName(ele.getAttribute(FACTORY_BEAN_ATTRIBUTE));
}
return bd;
}
protected boolean matchesPattern(String serviceId, Set<String> patterns) {
return patterns.stream().anyMatch(pattern -> PatternMatchUtils.simpleMatch(pattern, serviceId));
}