Created
January 16, 2017 23:52
-
-
Save mabn/0ad89733a3303a22f5906cde067ba21e to your computer and use it in GitHub Desktop.
path name provider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.getbase.tracing4j.spring; | |
import lombok.extern.slf4j.Slf4j; | |
import org.springframework.context.ApplicationListener; | |
import org.springframework.context.event.ContextRefreshedEvent; | |
import org.springframework.web.method.HandlerMethod; | |
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition; | |
import org.springframework.web.servlet.mvc.method.RequestMappingInfo; | |
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; | |
import java.lang.reflect.Method; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.Map.Entry; | |
@Slf4j | |
public class PathNameProvider implements ApplicationListener<ContextRefreshedEvent> { | |
private Map<Method, String> mappingNames; | |
// Event is used instead of regular injection because RequestMappingHandlerMapping is not available early enough | |
@Override | |
public void onApplicationEvent(ContextRefreshedEvent event) { | |
RequestMappingHandlerMapping mappings = event.getApplicationContext().getBean(RequestMappingHandlerMapping.class); | |
mappingNames = new HashMap<>(); | |
for(Entry<RequestMappingInfo, HandlerMethod> entry : mappings.getHandlerMethods().entrySet()) { | |
PatternsRequestCondition patterns = entry.getKey().getPatternsCondition(); | |
String pattern = patterns.getPatterns().iterator().next(); | |
mappingNames.put(entry.getValue().getMethod(), pattern); | |
} | |
} | |
/** | |
* Extract RequestMapping corresponding to given HandlerMethod. | |
* @param handler handler object obtained from HandlerInterceptorAdapter.preHandle argument | |
* @return mapping name, e.g. "/api/v1/orders" | |
*/ | |
public String getPathName(Object handler) { | |
if (handler instanceof HandlerMethod) { | |
HandlerMethod handlerMethod = (HandlerMethod) handler; | |
String name = mappingNames.get(handlerMethod.getMethod()); | |
if (name != null) { | |
return name; | |
} | |
} | |
log.warn("unknown handler {}", handler); | |
return "<unknown>"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment