-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRoleRequestCollector.java
More file actions
65 lines (53 loc) · 2.67 KB
/
RoleRequestCollector.java
File metadata and controls
65 lines (53 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.pitchain.common.collector;
import com.pitchain.common.annotation.RequiredRole;
import com.pitchain.common.constant.MemberRole;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.pattern.PathPattern;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@Component
public class RoleRequestCollector {
private final Map<MemberRole, Map<HttpMethod, Set<String>>> roleUriMap = new HashMap<>();
public RoleRequestCollector(ApplicationContext applicationContext) {
for (MemberRole role : MemberRole.values()) {
roleUriMap.put(role, new HashMap<>());
}
RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();
for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
collectRoleUris(entry, roleUriMap);
}
System.out.println();
}
private void collectRoleUris(Map.Entry<RequestMappingInfo, HandlerMethod> entry, Map<MemberRole, Map<HttpMethod, Set<String>>> roleUriMap) {
HandlerMethod handlerMethod = entry.getValue();
RequiredRole requiredRole = handlerMethod.getMethod().getAnnotation(RequiredRole.class);
if (requiredRole != null) {
MemberRole memberRole = requiredRole.value();
Map<HttpMethod, Set<String>> uriMap = roleUriMap.get(memberRole);
RequestMappingInfo info = entry.getKey();
for (RequestMethod requestMethod : info.getMethodsCondition().getMethods()) {
HttpMethod httpMethod = requestMethod.asHttpMethod();
Set<String> uris = uriMap.computeIfAbsent(httpMethod, k -> new HashSet<>());
for (PathPattern pathPattern : info.getPathPatternsCondition().getPatterns()) {
String uri = pathPattern.getPatternString();
uris.add(convertToAntPatternString(uri));
}
}
}
}
private static String convertToAntPatternString(String uri) {
return uri.replaceAll("\\{[^/]+\\}", "*");
}
public Map<MemberRole, Map<HttpMethod, Set<String>>> getRoleUriMap() {
return roleUriMap;
}
}