@Override public void onApplicationEvent ( ContextRefreshedEvent event ) { final RequestMappingHandlerMapping requestMappingHandlerMapping = applicationContext.getBean( RequestMappingHandlerMapping.class ); final Map< RequestMappingInfo, HandlerMethod > handlerMethods = requestMappingHandlerMapping.getHandlerMethods(); this.handlerMethods = handlerMethods; handlerMethods.keySet().forEach( mappingInfo -> { Map< Set< String >, Set< RequestMethod > > mapping = Collections.singletonMap( mappingInfo.getPatternsCondition().getPatterns() , this.getMethods( mappingInfo.getMethodsCondition().getMethods() ) ); requestMappingInfos.add( mapping ); } ); requestMappingUris.addAll( handlerMethods.keySet() .parallelStream() .map( mappingInfo -> mappingInfo.getPatternsCondition().getPatterns() ) .collect( Collectors.toList() ) ); }
public static List<OriginalRequestMappingInfo> of(RequestMappingHandlerMapping handlerMapping) { List<OriginalRequestMappingInfo> result = new ArrayList<OriginalRequestMappingInfo>(); for (Entry<RequestMappingInfo, HandlerMethod> entry : handlerMapping.getHandlerMethods().entrySet()) { RequestMappingInfo requestMappingInfo = entry.getKey(); OriginalRequestMappingInfo o = new OriginalRequestMappingInfo(); o.setSite(Site.of(requestMappingInfo.getPatternsCondition().getPatterns().iterator().next())); o.setMethods(requestMappingInfo.getMethodsCondition().getMethods()); o.setPatterns(requestMappingInfo.getPatternsCondition().getPatterns()); Set<String> params = new HashSet<>(); for (NameValueExpression<String> nameValueExpression : requestMappingInfo.getParamsCondition().getExpressions()) { params.add(nameValueExpression.toString()); } o.setParams(params); result.add(o); } return result.stream().sorted().collect(Collectors.toList()); }
/** * Create a {@link RequestMappingInfo} from the supplied * {@link RequestMapping @RequestMapping} annotation, which is either * a directly declared annotation, a meta-annotation, or the synthesized * result of merging annotation attributes within an annotation hierarchy. */ protected RequestMappingInfo createRequestMappingInfo( RequestMapping requestMapping, RequestCondition<?> customCondition) { return RequestMappingInfo .paths(resolveEmbeddedValuesInPatterns(requestMapping.path())) .methods(requestMapping.method()) .params(requestMapping.params()) .headers(requestMapping.headers()) .consumes(requestMapping.consumes()) .produces(requestMapping.produces()) .mappingName(requestMapping.name()) .customCondition(customCondition) .options(this.config) .build(); }
@Override protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) { RequestMapping annotation = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class); if (annotation != null) { return new RequestMappingInfo( new PatternsRequestCondition(annotation.value(), getUrlPathHelper(), getPathMatcher(), true, true), new RequestMethodsRequestCondition(annotation.method()), new ParamsRequestCondition(annotation.params()), new HeadersRequestCondition(annotation.headers()), new ConsumesRequestCondition(annotation.consumes(), annotation.headers()), new ProducesRequestCondition(annotation.produces(), annotation.headers()), null); } else { return null; } }
@Test public void useRegisteredSuffixPatternMatchInitialization() { Map<String, MediaType> fileExtensions = Collections.singletonMap("json", MediaType.APPLICATION_JSON); PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy(fileExtensions); ContentNegotiationManager manager = new ContentNegotiationManager(strategy); final Set<String> extensions = new HashSet<String>(); RequestMappingHandlerMapping hm = new RequestMappingHandlerMapping() { @Override protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) { extensions.addAll(getFileExtensions()); return super.getMappingForMethod(method, handlerType); } }; wac.registerSingleton("testController", ComposedAnnotationController.class); wac.refresh(); hm.setContentNegotiationManager(manager); hm.setUseRegisteredSuffixPatternMatch(true); hm.setApplicationContext(wac); hm.afterPropertiesSet(); assertEquals(Collections.singleton("json"), extensions); }
protected RequestMappingInfo createRequestMappingInfo(RequestMapping annotation, RequestCondition<?> customCondition,Object handler) { //XXX: not used RequestMapping if(annotation == null){ return createRequestMappingInfo(customCondition, handler); } String[] value = annotation.value(); String[] patterns = resolveEmbeddedValuesInPatterns(value); //XXX:thining //XXX:增加 RequestMapping value is null 时 默认使用方法名称(包括驼峰式和小写式) if(patterns == null ||(patterns != null && patterns.length == 0)){ patterns = getPathMaping(handler); } return new RequestMappingInfo( new PatternsRequestCondition(patterns, getUrlPathHelper(), getPathMatcher(), this.useSuffixPatternMatch(), this.useTrailingSlashMatch(), this.getFileExtensions()), new RequestMethodsRequestCondition(annotation.method()), new ParamsRequestCondition(annotation.params()), new HeadersRequestCondition(annotation.headers()), new ConsumesRequestCondition(annotation.consumes(), annotation.headers()), new ProducesRequestCondition(annotation.produces(), annotation.headers(), this.getContentNegotiationManager()), customCondition); }
private void loadMappedRequestFromRequestMappingInfoSet(Set<RequestMappingInfo> requestMappingInfoSet) { for (RequestMappingInfo requestMappingInfo : requestMappingInfoSet) { String patternUrl = this.stringifyPatternsCondition(requestMappingInfo.getPatternsCondition()); if (patternUrl.contains("{") || patternUrl.contains("}") || !patternUrl.startsWith(DEFAULT_ADMIN_URL) || patternUrl.equals(DEFAULT_ADMIN_URL)) { continue; } String name = patternUrl.replace(DEFAULT_ADMIN_URL + "/", ""); name = name.replace("/", "-"); MappedRequestInfo mappedRequestInfo = new MappedRequestInfo(name, patternUrl); if (mappedRequests.contains(mappedRequestInfo) || mappedRequestInfo.getName().equals("welcome")) { continue; } mappedRequests.add(mappedRequestInfo); } }
/** * Override to only populate the first handler given for a mapping. * * {@inheritDoc} */ @Override protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) { HandlerMethod newHandlerMethod = super.createHandlerMethod(handler, method); this.handlerMethods.put(mapping, newHandlerMethod); if (logger.isInfoEnabled()) { logger.info("Mapped \"" + mapping + "\" onto " + newHandlerMethod); } if (!this.handlerMethods.containsKey(mapping)) { Set<String> patterns = super.getMappingPathPatterns(mapping); for (String pattern : patterns) { if (!super.getPathMatcher().isPattern(pattern)) { this.urlMap.add(pattern, mapping); } } } }
private void setResourcePatternByRequestMappingInfo(Class<?> codeClass, DefaultIPermission<?> perm, Entry<RequestMappingInfo, HandlerMethod> entry){ /*if(perm.getResourcesPattern()!=null){ List<UrlResourceInfo> infos = urlResourceInfoParser.parseToUrlResourceInfos(perm.getResourcesPattern()); //如果自定义了,忽略自动解释 if(!infos.isEmpty()){ String urls = this.urlResourceInfoParser.parseToString(infos); perm.setResourcesPattern(urls); } return ; }*/ List<UrlResourceInfo> infos = urlResourceInfoParser.parseToUrlResourceInfos(perm.getResourcesPattern()); Set<String> urlPattterns = entry.getKey().getPatternsCondition().getPatterns(); if(urlPattterns.size()==1){ String url = urlPattterns.stream().findFirst().orElse(""); Optional<RequestMethod> method = getFirstMethod(entry.getKey()); infos.add(new UrlResourceInfo(url, method.isPresent()?method.get().name():null)); }else{ //超过一个url映射的,不判断方法 urlPattterns.stream().forEach(url->infos.add(new UrlResourceInfo(url))); } String urls = this.urlResourceInfoParser.parseToString(infos); perm.setResourcesPattern(urls); }
@Override public RequestMappingInfo combine(Method method, Class<?> handlerType, RequestMappingInfo info) { if(info==null){ return info; } Optional<AnnotationAttributes> webApiOpt = findWebApiAttrs(method, handlerType); if(!webApiOpt.isPresent()){ return info; } AnnotationAttributes webApi = webApiOpt.get(); String prefixPath = webApi.getString("prefixPath"); if(StringUtils.isBlank(prefixPath)){ return info; } prefixPath = SpringUtils.resolvePlaceholders(applicationContext, prefixPath); if(StringUtils.isBlank(prefixPath)){ return info; } RequestMappingInfo combinerInfo = RequestMappingCombiner.createRequestMappingInfo(prefixPath, method, handlerType) .combine(info); return combinerInfo; }
@SuppressWarnings("unchecked") @Override public void onHandlerMethodsInitialized(Map<RequestMappingInfo, HandlerMethod> handlerMethods) { for(HandlerMethod hm : handlerMethods.values()){ Optional<AnnotationAttributes> attrsOpt = findInterceptorAttrs(hm); if(attrsOpt.isPresent()){ AnnotationAttributes attrs = attrsOpt.get(); Class<? extends MvcInterceptor>[] interClasses = (Class<? extends MvcInterceptor>[])attrs.get("value"); List<? extends MvcInterceptor> interceptors = Stream.of(interClasses) .flatMap(cls->{ List<? extends MvcInterceptor> inters = SpringUtils.getBeans(applicationContext, cls); if(LangUtils.isEmpty(inters)){ throw new BaseException("MvcInterceptor not found for : " + cls); } return inters.stream(); }) .collect(Collectors.toList()); if(!interceptors.isEmpty()){ HandlerMethodInterceptorMeta meta = new HandlerMethodInterceptorMeta(hm, interceptors); interceptorMetaCaces.put(hm.getMethod(), meta); } } } }
@Override protected void doLogging(Map<RequestMappingInfo, HandlerMethod> requestMappingInfoAndHandlerMethodMap){ Map<String, String> urlAndClientCacheMap = HandlerMappingUtil.buildUrlAndAnnotationStringMap( requestMappingInfoAndHandlerMethodMap, ClientCache.class, ClientCacheToStringBuilder.INSTANCE); if (isNullOrEmpty(urlAndClientCacheMap)){ LOGGER.info("urlAndClientCacheMap is null or empty"); return; } //--------------------------------------------------------------- LOGGER.info( "url And ClientCache,size:[{}], info:{}", urlAndClientCacheMap.size(), JsonUtil.format(sortMapByKeyAsc(urlAndClientCacheMap))); }
/** * 获得 request mapping handler mapping info map for LOGGER. * * @param webApplicationContext * the web application context * @return the request mapping handler mapping info map for log */ public static final Map<String, Object> getRequestMappingHandlerMappingInfoMapForLog(WebApplicationContext webApplicationContext){ RequestMappingHandlerMapping requestMappingHandlerMapping = webApplicationContext.getBean(RequestMappingHandlerMapping.class); Map<String, Object> mappingInfoMap = newLinkedHashMap(); mappingInfoMap.put("useRegisteredSuffixPatternMatch()", requestMappingHandlerMapping.useRegisteredSuffixPatternMatch()); mappingInfoMap.put("useSuffixPatternMatch()", requestMappingHandlerMapping.useSuffixPatternMatch()); mappingInfoMap.put("useTrailingSlashMatch()", requestMappingHandlerMapping.useTrailingSlashMatch()); mappingInfoMap.put("getDefaultHandler()", requestMappingHandlerMapping.getDefaultHandler()); mappingInfoMap.put("getFileExtensions()", requestMappingHandlerMapping.getFileExtensions()); mappingInfoMap.put("getOrder()", requestMappingHandlerMapping.getOrder()); mappingInfoMap.put("getPathMatcher()", requestMappingHandlerMapping.getPathMatcher()); mappingInfoMap.put("getUrlPathHelper()", requestMappingHandlerMapping.getUrlPathHelper()); //--------------------------------------------------------------- Map<String, RequestMappingInfo> methodAndRequestMappingInfoMapMap = buildMethodAndRequestMappingInfoMap( requestMappingHandlerMapping); mappingInfoMap.put("methodAndRequestMappingInfoMapMap", methodAndRequestMappingInfoMapMap); return mappingInfoMap; }
/** * key 是handle 方法,value 是 RequestMappingInfo 信息. * * @param requestMappingHandlerMapping * the request mapping handler mapping * @return the map< string, request mapping info> * @see org.springframework.web.servlet.mvc.method.RequestMappingInfo * @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#createRequestMappingInfo(RequestMapping, * RequestCondition) * @since 1.5.4 */ private static Map<String, RequestMappingInfo> buildMethodAndRequestMappingInfoMap( RequestMappingHandlerMapping requestMappingHandlerMapping){ Map<String, RequestMappingInfo> methodAndRequestMappingInfoMap = newLinkedHashMap(); //--------------------------------------------------------------- Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods(); for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()){ RequestMappingInfo requestMappingInfo = entry.getKey(); HandlerMethod handlerMethod = entry.getValue(); methodAndRequestMappingInfoMap.put(handlerMethod.toString(), requestMappingInfo); } if (LOGGER.isInfoEnabled()){ Collection<RequestMappingInfo> requestMappingInfoCollection = methodAndRequestMappingInfoMap.values(); String format = JsonUtil.format(getPropertyValueList(requestMappingInfoCollection, "patternsCondition.patterns")); LOGGER.info("all requestMapping value:{}", format); } return methodAndRequestMappingInfoMap; }
@Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent){ if (!LOGGER.isInfoEnabled()){ return; } ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext(); Map<RequestMappingInfo, HandlerMethod> requestMappingInfoAndHandlerMethodMap = buildHandlerMethods(applicationContext); if (isNullOrEmpty(requestMappingInfoAndHandlerMethodMap)){ LOGGER.info("requestMappingInfo And HandlerMethod Map is null or empty!!"); return; } //--------------------------------------------------------------- doLogging(requestMappingInfoAndHandlerMethodMap); }
@Bean public WebMvcRegistrationsAdapter webMvcRegistrationsAdapter() { return new WebMvcRegistrationsAdapter() { @Override public RequestMappingHandlerMapping getRequestMappingHandlerMapping() { return new RequestMappingHandlerMapping() { @Override protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) { if (method.getDeclaringClass().isAnnotationPresent(SpringRestClientEnabled.class)) { return; // by pass SpringRestClientEnabled interface } super.registerHandlerMethod(handler, method, mapping); } }; } }; }
@Override protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) { RequestMappingInfo info = super.getMappingForMethod(method, handlerType); if (info == null) return null; ApiVersion methodAnnotation = AnnotationUtils.findAnnotation(method, ApiVersion.class); if (methodAnnotation != null) { RequestCondition<?> methodCondition = getCustomMethodCondition(method); // Concatenate our ApiVersion with the usual request mapping info = createApiVersionInfo(methodAnnotation, methodCondition).combine(info); } else { ApiVersion typeAnnotation = AnnotationUtils.findAnnotation(handlerType, ApiVersion.class); if (typeAnnotation != null) { RequestCondition<?> typeCondition = getCustomTypeCondition(handlerType); // Concatenate our ApiVersion with the usual request mapping info = createApiVersionInfo(typeAnnotation, typeCondition).combine(info); } } return info; }
private RequestMappingInfo getMappingForMethod(Object handler, Method method, Class<?> handlerType) { Object handlerObj = (handler instanceof String) ? getApplicationContext().getBean((String) handler) : handler; EntityControllerImpl<?,?> controller = (EntityControllerImpl<?,?>)handlerObj; RequestMappingInfo info = null; RequestMapping methodAnnotation = createMethodLevelRequestMapping(controller, method); //logger.debug(methodAnnotation+" "+handler+" "+controller+" "+method.getName()+" "+controller.getMetamodel().getTopLevelMapping()); if (methodAnnotation != null) { info = createRequestMappingInfo(methodAnnotation, null); //RequestMapping typeAnnotation = createTypeLevelRequestMapping(controller, handlerType); //info = createRequestMappingInfo(typeAnnotation, null).combine(info); //logger.info("****1 "+controller); //logger.info("****2 "+method); //logger.info("****3 "+typeAnnotation.value()); //logger.info("****4 "+methodAnnotation.value()); } return info; }
@RequestMapping(value = "/api/admin/endpoint-info", method = RequestMethod.GET) public EndpointsInfo getAllEndpoints() { List<EndpointInfo> res = new ArrayList<>(); Set<String> pathVariables = new TreeSet<>(); for (Entry<RequestMappingInfo, HandlerMethod> kv : handlerMapping.getHandlerMethods().entrySet()) { for (String p : kv.getKey().getPatternsCondition().getPatterns()) { pathVariables.addAll(extractPathVariables(p)); } res.add(new EndpointInfo(kv)); } Collections.sort(res); return new EndpointsInfo(pathVariables, res); }
/** * Uses method and type-level @{@link RequestMapping} annotations to create * the RequestMappingInfo. * @return the created RequestMappingInfo, or {@code null} if the method * does not have a {@code @RequestMapping} annotation. * @see #getCustomMethodCondition(Method) * @see #getCustomTypeCondition(Class) */ @Override protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) { RequestMappingInfo info = null; RequestMapping methodAnnotation = AnnotationUtils.findAnnotation(method, RequestMapping.class); if (methodAnnotation != null) { RequestCondition<?> methodCondition = getCustomMethodCondition(method); info = createRequestMappingInfo(methodAnnotation, methodCondition); RequestMapping typeAnnotation = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class); if (typeAnnotation != null) { RequestCondition<?> typeCondition = getCustomTypeCondition(handlerType); info = createRequestMappingInfo(typeAnnotation, typeCondition).combine(info); } } return info; }
@PostConstruct private void initApiMappings() { Map<RequestMappingInfo, HandlerMethod> requestMappedHandlers = this.handlerMapping.getHandlerMethods(); for (Map.Entry<RequestMappingInfo, HandlerMethod> requestMappedHandlerEntry : requestMappedHandlers.entrySet()) { RequestMappingInfo requestMappingInfo = requestMappedHandlerEntry.getKey(); HandlerMethod handlerMethod = requestMappedHandlerEntry.getValue(); Class<?> handlerMethodBeanClazz = handlerMethod.getBeanType(); if (handlerMethodBeanClazz == this.getClass()) { continue; } String controllerName = handlerMethodBeanClazz.getSimpleName(); Set<String> mappedRequests = requestMappingInfo.getPatternsCondition().getPatterns(); SortedSet<RequestMappedUri> alreadyMappedRequests = this.apiMappings.get(controllerName); if (alreadyMappedRequests == null) { alreadyMappedRequests = new TreeSet<RequestMappedUri>(RequestMappedUri.MAPPED_URI_ORDER); this.apiMappings.put(controllerName, alreadyMappedRequests); } alreadyMappedRequests.addAll(createRequestMappedApis(handlerMethod, mappedRequests)); } }
private static WadlResource mapToWadlResource(RequestMappingInfo mappingInfo, HandlerMethod handlerMethod, WadlTypeMapper wadlTypeMapper) { WadlResource wadlResource = new WadlResource(); Set<String> pattern = mappingInfo.getPatternsCondition().getPatterns(); for (String uri : pattern) { wadlResource.setPath(uri); } Set<MediaType> consumableMediaTypes = mappingInfo.getConsumesCondition().getConsumableMediaTypes(); Set<MediaType> producibleMediaTypes = mappingInfo.getProducesCondition().getProducibleMediaTypes(); Set<RequestMethod> httpMethods = mappingInfo.getMethodsCondition().getMethods(); for (RequestMethod httpMethod : httpMethods) { WadlMethod wadlMethod = mapToWadlMethod(httpMethod, handlerMethod.getMethod(), consumableMediaTypes, producibleMediaTypes, wadlTypeMapper); wadlResource.getMethodOrResource().add(wadlMethod); } return wadlResource; }
protected RequestMappingInfo createRequestMappingInfo(String pattern) { String[] patterns = (null == pattern) ? null : this.resolveEmbeddedValuesInPatterns(new String[] { pattern }); return new RequestMappingInfo(new PatternsRequestCondition(patterns, this.getUrlPathHelper(), this.getPathMatcher(), this.useSuffixPatternMatch(), this.useTrailingSlashMatch(), this.getFileExtensions()), null, null, null, null, null, null); }
@PostConstruct public void init() { Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods(); handlerMethods.forEach((k, v) -> { List<String> urls = k.getPatternsCondition().getPatterns().stream().sorted().collect(Collectors.toList()); methodRestfulUrls.put(v.getMethod(), urls); restfulUrlCounters.put(urls, new AtomicInteger(INT_ZERO)); }); }
protected RequestMappingInfo createRequestMappingInfo(String pattern) { String[] patterns = (null == pattern) ? null : this.resolveEmbeddedValuesInPatterns(new String[]{pattern}); return new RequestMappingInfo(new PatternsRequestCondition(patterns, this.getUrlPathHelper(), this.getPathMatcher(), this.useSuffixPatternMatch(), this.useTrailingSlashMatch(), this.getFileExtensions()), null, null, null, null, null, null); }
private List<String> getAllRequestMappingInfo() { AbstractHandlerMethodMapping<RequestMappingInfo> objHandlerMethodMapping = (AbstractHandlerMethodMapping<RequestMappingInfo>)applicationContext.getBean("requestMappingHandlerMapping"); Map<RequestMappingInfo, HandlerMethod> mapRet = objHandlerMethodMapping.getHandlerMethods(); List<String> res = new ArrayList<String>(); for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : mapRet.entrySet()) { String uri = entry.getKey().toString().replace("{", "").replace("[", "").replace("}","").replace("]",""); String []temp = uri.split(","); res.add(temp[0]); } return res; }
public static HomeModuleExtension create(RequestMappingHandlerMapping mapping) { HomeModuleExtension ext = new HomeModuleExtension(); Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods(); for (RequestMappingInfo info : handlerMethods.keySet()) { Set<String> patterns = info.getPatternsCondition().getPatterns(); for (String pattern : patterns) { ext.addPath(pattern); } } return ext; }
private Function<? super RequestMappingInfoHandlerMapping, Iterable<Map.Entry<RequestMappingInfo, HandlerMethod>>> toMappingEntries() { return new Function<RequestMappingInfoHandlerMapping, Iterable<Map.Entry<RequestMappingInfo, HandlerMethod>>>() { @Override public Iterable<Map.Entry<RequestMappingInfo, HandlerMethod>> apply( RequestMappingInfoHandlerMapping input) { return input.getHandlerMethods().entrySet(); } }; }
private Function<Map.Entry<RequestMappingInfo, HandlerMethod>, RequestHandler> toRequestHandler() { return new Function<Map.Entry<RequestMappingInfo, HandlerMethod>, RequestHandler>() { @Override public RequestHandler apply(Map.Entry<RequestMappingInfo, HandlerMethod> input) { return new RequestHandler(input.getKey(), input.getValue()); } }; }
@Override public void afterPropertiesSet() { this.config = new RequestMappingInfo.BuilderConfiguration(); this.config.setPathHelper(getUrlPathHelper()); this.config.setPathMatcher(getPathMatcher()); this.config.setSuffixPatternMatch(this.useSuffixPatternMatch); this.config.setTrailingSlashMatch(this.useTrailingSlashMatch); this.config.setRegisteredSuffixPatternMatch(this.useRegisteredSuffixPatternMatch); this.config.setContentNegotiationManager(getContentNegotiationManager()); super.afterPropertiesSet(); }
/** * Uses method and type-level @{@link RequestMapping} annotations to create * the RequestMappingInfo. * @return the created RequestMappingInfo, or {@code null} if the method * does not have a {@code @RequestMapping} annotation. * @see #getCustomMethodCondition(Method) * @see #getCustomTypeCondition(Class) */ @Override protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) { RequestMappingInfo info = createRequestMappingInfo(method); if (info != null) { RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType); if (typeInfo != null) { info = typeInfo.combine(info); } } return info; }
@Override protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) { HandlerMethod handlerMethod = createHandlerMethod(handler, method); CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getBeanType(), CrossOrigin.class); CrossOrigin methodAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, CrossOrigin.class); if (typeAnnotation == null && methodAnnotation == null) { return null; } CorsConfiguration config = new CorsConfiguration(); updateCorsConfig(config, typeAnnotation); updateCorsConfig(config, methodAnnotation); if (CollectionUtils.isEmpty(config.getAllowedOrigins())) { config.setAllowedOrigins(Arrays.asList(CrossOrigin.DEFAULT_ORIGINS)); } if (CollectionUtils.isEmpty(config.getAllowedMethods())) { for (RequestMethod allowedMethod : mappingInfo.getMethodsCondition().getMethods()) { config.addAllowedMethod(allowedMethod.name()); } } if (CollectionUtils.isEmpty(config.getAllowedHeaders())) { config.setAllowedHeaders(Arrays.asList(CrossOrigin.DEFAULT_ALLOWED_HEADERS)); } if (config.getAllowCredentials() == null) { config.setAllowCredentials(CrossOrigin.DEFAULT_ALLOW_CREDENTIALS); } if (config.getMaxAge() == null) { config.setMaxAge(CrossOrigin.DEFAULT_MAX_AGE); } return config; }
@Test public void resolveRequestMappingViaComposedAnnotation() throws Exception { Class<?> clazz = ComposedAnnotationController.class; Method method = clazz.getMethod("handleInput"); RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, clazz); assertNotNull(info); assertEquals(Collections.singleton("/input"), info.getPatternsCondition().getPatterns()); }
@Override protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) { RequestMappingInfo info = null; RequestMapping methodAnnotation = AnnotationUtils.findAnnotation(method, RequestMapping.class); if (methodAnnotation != null) { info = createRequestMappingInfo2(methodAnnotation, method); RequestMapping typeAnnotation = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class); if (typeAnnotation != null) { info = createRequestMappingInfo2(typeAnnotation, null).combine(info); } } return info; }
/** * Created a RequestMappingInfo from a RequestMapping annotation. */ protected RequestMappingInfo createRequestMappingInfo2(RequestMapping annotation, Method method) { String[] patterns; if (method != null && annotation.value().length == 0) { patterns = new String[] { this.createPattern(method.getName()) }; } else { patterns = resolveEmbeddedValuesInPatterns(annotation.value()); } Map<String, String> headerMap = new LinkedHashMap<String, String>(); ExtensiveDomain extensiveDomain = new ExtensiveDomain(); requestMappingInfoBuilder.getHeaders(annotation, method, extensiveDomain, headerMap); // System.out.println("headerMap:" + headerMap); String[] headers = new String[headerMap.size()]; { int i = 0; for (Entry<String, String> entry : headerMap.entrySet()) { String header = entry.getKey() + "=" + entry.getValue(); headers[i] = header; i++; } } RequestCondition<?> customCondition = new ServerNameRequestCondition(extensiveDomain, headers); return new RequestMappingInfo(new PatternsRequestCondition(patterns, getUrlPathHelper(), getPathMatcher(), false, this.useTrailingSlashMatch(), this.getFileExtensions()), new RequestMethodsRequestCondition(annotation.method()), new ParamsRequestCondition(annotation.params()), new HeadersRequestCondition(), new ConsumesRequestCondition(annotation.consumes(), headers), new ProducesRequestCondition(annotation.produces(), headers, getContentNegotiationManager()), customCondition); }
@Test public void getMappingForMethod() throws SecurityException, NoSuchMethodException { Method method = LeopardHandlerMappingTest.class.getDeclaredMethod("test"); RequestMappingInfo requestMappingInfo = leopardHandlerMapping.getMappingForMethod(method, LeopardHandlerMappingTest.class); Set<String> patterns = requestMappingInfo.getPatternsCondition().getPatterns(); Assert.assertEquals("[/test.do]", patterns.toString()); }
@Test public void getMappingForMethod3() throws SecurityException, NoSuchMethodException { Method method = LeopardHandlerMappingTest.class.getDeclaredMethod("test"); RequestMappingInfo requestMappingInfo = leopardHandlerMapping.getMappingForMethod(method, TestController.class); Set<String> patterns = requestMappingInfo.getPatternsCondition().getPatterns(); Assert.assertEquals("[/test.do]", patterns.toString()); }
@Override @Deprecated protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) { if (mapping == null) { return; } String[] patterns = getPatterns(handler, mapping); super.registerHandlerMethod(handler, method, withNewPatterns(mapping, patterns)); }