Skip to content

Instantly share code, notes, and snippets.

@micpango
Created May 21, 2013 07:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micpango/5617999 to your computer and use it in GitHub Desktop.
Save micpango/5617999 to your computer and use it in GitHub Desktop.
Service for listing all spring-mvc url mappings
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.base.Function;
import org.springframework.stereotype.Service;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.method.HandlerMethodSelector;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import static com.google.common.collect.Lists.transform;
@Service
public class PathMatcherService extends RequestMappingHandlerMapping {
public List<Map<String, String>> findAllPaths() {
String[] beanNames = getApplicationContext().getBeanNamesForType(Object.class);
List<Map<String, String>> paths = new ArrayList<>();
for (String beanName : beanNames) {
if (isHandler(getApplicationContext().getType(beanName))) {
paths.addAll(getPathsForHandler(beanName));
}
}
return paths;
}
private List<Map<String, String>> getPathsForHandler(final Object handler) {
final Class<?> handlerType = (handler instanceof String) ?
getApplicationContext().getType((String) handler) : handler.getClass();
final Class<?> userType = ClassUtils.getUserClass(handlerType);
final Set<Method> methods = HandlerMethodSelector.selectMethods(userType, new ReflectionUtils.MethodFilter() {
public boolean matches(Method method) {
return getMappingForMethod(method, userType) != null;
}
});
final List<Method> methodList = new ArrayList<>();
methodList.addAll(methods);
return transform(methodList, new Function<Method, Map<String, String>>() {
@Override public Map<String, String> apply(final Method method) {
final RequestMappingInfo info = getMappingForMethod(method, userType);
return new HashMap<String, String>() {{
final String path = info.getPatternsCondition().getPatterns().toArray()[0].toString();
put("verb", info.getMethodsCondition().toString());
put("path", path);
put("controller", (String) handler);
put("action", method.getName());
put("regexp", createRegExp(path));
}};
}
});
}
private String createRegExp(String path) {
return path.replaceAll("\\{.*?\\}", "\\\\w+");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment