Java Code Examples for org.springframework.web.servlet.mvc.method.RequestMappingInfo

The following examples show how to use org.springframework.web.servlet.mvc.method.RequestMappingInfo. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private RequestMappingInfo createRequestMappingInfo(String codelessName, String action) {
    RequestMappingInfo.Builder builder = RequestMappingInfo
        .paths(resolveEmbeddedValuesInPatterns(new String[] {"/" + codelessName + "/" + action}));
    if ("add".equals(action)) {
        builder.methods(RequestMethod.POST);
    }
    if ("modify".equals(action)) {
        builder.methods(RequestMethod.PUT);
    }
    if ("delete".equals(action)) {
        builder.methods(RequestMethod.DELETE);
    }
    if ("get".equals(action) || Pattern.matches("list.*", action)) {
        builder.methods(RequestMethod.GET);
    }
    builder.mappingName("[" + codelessEntityMetadataMap.get(codelessName).getEntityClass().getSimpleName() + "] "
        + action
        + " mapping");
    return builder.options(this.config).build();
}
 
Example 2
/**
 * 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
@Nullable
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);
		}
		String prefix = getPathPrefix(handlerType);
		if (prefix != null) {
			info = RequestMappingInfo.paths(prefix).build().combine(info);
		}
	}
	return info;
}
 
Example 3
@Override
protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) {
	HandlerMethod handlerMethod = createHandlerMethod(handler, method);
	Class<?> beanType = handlerMethod.getBeanType();
	CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(beanType, 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.getAllowedMethods())) {
		for (RequestMethod allowedMethod : mappingInfo.getMethodsCondition().getMethods()) {
			config.addAllowedMethod(allowedMethod.name());
		}
	}
	return config.applyPermitDefaultValues();
}
 
Example 4
Source Project: spring-analysis-note   Source File: CrossOriginTests.java    License: MIT License 6 votes vote down vote up
@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;
	}
}
 
Example 5
Source Project: spring-boot-demo   Source File: RbacAuthorityService.java    License: MIT License 6 votes vote down vote up
/**
 * 获取 所有URL Mapping,返回格式为{"/test":["GET","POST"],"/sys":["GET","DELETE"]}
 *
 * @return {@link ArrayListMultimap} 格式的 URL Mapping
 */
private Multimap<String, String> allUrlMapping() {
    Multimap<String, String> urlMapping = ArrayListMultimap.create();

    // 获取url与类和方法的对应信息
    Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();

    handlerMethods.forEach((k, v) -> {
        // 获取当前 key 下的获取所有URL
        Set<String> url = k.getPatternsCondition()
                .getPatterns();
        RequestMethodsRequestCondition method = k.getMethodsCondition();

        // 为每个URL添加所有的请求方法
        url.forEach(s -> urlMapping.putAll(s, method.getMethods()
                .stream()
                .map(Enum::toString)
                .collect(Collectors.toList())));
    });

    return urlMapping;
}
 
Example 6
public List<String> xssMatches() {
    List<String> urls = new ArrayList<String >();
    Map<RequestMappingInfo, HandlerMethod> handlerMethods =
            this.requestMappingHandlerMapping.getHandlerMethods();

    for(Map.Entry<RequestMappingInfo, HandlerMethod> item : handlerMethods.entrySet()) {
        RequestMappingInfo mapping = item.getKey();
        HandlerMethod method = item.getValue();
        if (mapping.getPatternsCondition() != null && mapping.getPatternsCondition().getPatterns() != null) {
            for (String urlPattern : mapping.getPatternsCondition().getPatterns()) {
                if(method.hasMethodAnnotation(XxsFilter.class)) {
                    urls.add(urlPattern);
                }
            }
        }
    }
    return urls;
}
 
Example 7
private RequestMappingInfo assertComposedAnnotationMapping(String methodName, String path,
		RequestMethod requestMethod) throws Exception {

	Class<?> clazz = ComposedAnnotationController.class;
	Method method = ClassUtils.getMethod(clazz, methodName, (Class<?>[]) null);
	RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, clazz);

	assertNotNull(info);

	Set<String> paths = info.getPatternsCondition().getPatterns();
	assertEquals(1, paths.size());
	assertEquals(path, paths.iterator().next());

	Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
	assertEquals(1, methods.size());
	assertEquals(requestMethod, methods.iterator().next());

	return info;
}
 
Example 8
Source Project: onetwo   Source File: PermissionHandlerMappingListener.java    License: Apache License 2.0 6 votes vote down vote up
public void onHandlerMethodsInitialized(Map<RequestMappingInfo, HandlerMethod> handlerMethods) {
	this.permissionManager.build();
	for(Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()){
		/*if (entry.getValue().getBeanType().getName().contains("SysSettingsController")) {
			System.out.println("test");
		}*/
		ByPermissionClass permClassInst = entry.getValue().getMethodAnnotation(ByPermissionClass.class);
		if(permClassInst==null){
			continue ;
		}
		for(Class<?> codeClass : permClassInst.value()){
			this.autoConifgPermission(codeClass, entry, permClassInst);
		}
	}
	this.permissionManager.getMemoryRootMenu().forEach(rootMenu->{
		logger.info("menu:\n{}", rootMenu.toTreeString("\n"));
	});
}
 
Example 9
Source Project: onetwo   Source File: PermissionHandlerMappingListener.java    License: Apache License 2.0 6 votes vote down vote up
private void setResourcePatternByRequestMappingInfo(Class<?> codeClass, IPermission 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);
}
 
Example 10
Source Project: springdoc-openapi   Source File: OpenApiResource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Calculate path.
 *
 * @param restControllers the rest controllers
 * @param map the map
 */
protected void calculatePath(Map<String, Object> restControllers, Map<RequestMappingInfo, HandlerMethod> map) {
	for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : map.entrySet()) {
		RequestMappingInfo requestMappingInfo = entry.getKey();
		HandlerMethod handlerMethod = entry.getValue();
		PatternsRequestCondition patternsRequestCondition = requestMappingInfo.getPatternsCondition();
		Set<String> patterns = patternsRequestCondition.getPatterns();
		Map<String, String> regexMap = new LinkedHashMap<>();
		for (String pattern : patterns) {
			String operationPath = PathUtils.parsePath(pattern, regexMap);
			if (((actuatorProvider.isPresent() && actuatorProvider.get().isRestController(operationPath))
					|| isRestController(restControllers, handlerMethod, operationPath))
					&& isPackageToScan(handlerMethod.getBeanType().getPackage())
					&& isPathToMatch(operationPath)) {
				Set<RequestMethod> requestMethods = requestMappingInfo.getMethodsCondition().getMethods();
				// default allowed requestmethods
				if (requestMethods.isEmpty())
					requestMethods = this.getDefaultAllowedHttpMethods();
				calculatePath(handlerMethod, operationPath, requestMethods);
			}
		}
	}
}
 
Example 11
Source Project: pinpoint   Source File: ApisController.java    License: Apache License 2.0 6 votes vote down vote up
@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));
    }
}
 
Example 12
Source Project: spring-boot-demo   Source File: RbacAuthorityService.java    License: MIT License 6 votes vote down vote up
/**
 * 获取 所有URL Mapping,返回格式为{"/test":["GET","POST"],"/sys":["GET","DELETE"]}
 *
 * @return {@link ArrayListMultimap} 格式的 URL Mapping
 */
private Multimap<String, String> allUrlMapping() {
    Multimap<String, String> urlMapping = ArrayListMultimap.create();

    // 获取url与类和方法的对应信息
    Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();

    handlerMethods.forEach((k, v) -> {
        // 获取当前 key 下的获取所有URL
        Set<String> url = k.getPatternsCondition()
                .getPatterns();
        RequestMethodsRequestCondition method = k.getMethodsCondition();

        // 为每个URL添加所有的请求方法
        url.forEach(s -> urlMapping.putAll(s, method.getMethods()
                .stream()
                .map(Enum::toString)
                .collect(Collectors.toList())));
    });

    return urlMapping;
}
 
Example 13
/**
 * 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();
}
 
Example 14
/**
 * 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
@Nullable
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);
		}
		String prefix = getPathPrefix(handlerType);
		if (prefix != null) {
			info = RequestMappingInfo.paths(prefix).build().combine(info);
		}
	}
	return info;
}
 
Example 15
@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<>();

	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);
}
 
Example 16
private RequestMappingInfo assertComposedAnnotationMapping(String methodName, String path,
		RequestMethod requestMethod) throws Exception {

	Class<?> clazz = ComposedAnnotationController.class;
	Method method = clazz.getMethod(methodName);
	RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, clazz);

	assertNotNull(info);

	Set<String> paths = info.getPatternsCondition().getPatterns();
	assertEquals(1, paths.size());
	assertEquals(path, paths.iterator().next());

	Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
	assertEquals(1, methods.size());
	assertEquals(requestMethod, methods.iterator().next());

	return info;
}
 
Example 17
@Test
public void getTest() {
    RequestMappingHandlerMapping handlerMapping = Mockito.mock(RequestMappingHandlerMapping.class);
    ExposedEndpointsController controller = new ExposedEndpointsController(new Gson(), handlerMapping);

    String endpoint1 = "/api/test";
    String endpoint2 = "/api/other/test";

    Map<RequestMappingInfo, HandlerMethod> handlerMethods = new HashMap<>();
    RequestMappingInfo info = new RequestMappingInfo(new PatternsRequestCondition(endpoint1, endpoint2), new RequestMethodsRequestCondition(RequestMethod.GET, RequestMethod.POST), null, null, null, null, null);
    handlerMethods.put(info, null);

    Mockito.when(handlerMapping.getHandlerMethods()).thenReturn(handlerMethods);

    ResponseEntity<String> responseEntity = controller.get();
    Assertions.assertTrue(StringUtils.isNotBlank(responseEntity.getBody()), "Expected the response body to contain json");
}
 
Example 18
Source Project: api-mock-util   Source File: RequestMappingService.java    License: Apache License 2.0 6 votes vote down vote up
public boolean hasApiRegistered(String api,String requestMethod){
    notBlank(api,"api cant not be null");
    notBlank(requestMethod,"requestMethod cant not be null");

    RequestMappingHandlerMapping requestMappingHandlerMapping = webApplicationContext.getBean(RequestMappingHandlerMapping.class);
    Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
    for (RequestMappingInfo info : map.keySet()) {
        for(String pattern :info.getPatternsCondition().getPatterns()){
            if(pattern.equalsIgnoreCase(api)){ // 匹配url
                if(info.getMethodsCondition().getMethods().contains(getRequestMethod(requestMethod))){ // 匹配requestMethod
                    return true;
                }
            }
        }
    }

    return false;
}
 
Example 19
protected RequestMappingInfo createRequestMappingInfoByApiMethodAnno(RequestMapping requestMapping, RequestCondition<?> customCondition,
                                                                     Method method) {
    String[] patterns = resolveEmbeddedValuesInPatterns(requestMapping.value());
    if (!method.isAnnotationPresent(RequestMapping.class) || CollectionUtil.isEmpty(patterns)) {
        RequestMappingResolveResult methodParsered = RequestMappingResolver.resolveOwnPath(method);
        String path = methodParsered.getPath();
        patterns = new String[] { path };
    }

    return new RequestMappingInfo(
        new PatternsRequestCondition(patterns, getUrlPathHelper(), getPathMatcher(), this.useSuffixPatternMatch, this.useTrailingSlashMatch,
            this.fileExtensions),
        new RequestMethodsRequestCondition(requestMapping.method()), new ParamsRequestCondition(requestMapping.params()),
        new HeadersRequestCondition(requestMapping.headers()), new ConsumesRequestCondition(requestMapping.consumes(), requestMapping.headers()),
        new ProducesRequestCondition(requestMapping.produces(), requestMapping.headers(), this.contentNegotiationManager), customCondition);
}
 
Example 20
Source Project: spring4-understanding   Source File: CrossOriginTests.java    License: Apache License 2.0 6 votes vote down vote up
@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;
	}
}
 
Example 21
Source Project: onetwo   Source File: WebApiRequestMappingCombiner.java    License: Apache License 2.0 6 votes vote down vote up
@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, info)
															.combine(info);
	return combinerInfo;
}
 
Example 22
Source Project: halo-docs   Source File: OperationTranslation.java    License: Apache License 2.0 5 votes vote down vote up
public OperationTranslation(SpringMVCTranslation parent, RequestMappingInfo mapping, HandlerMethod handler, Method method, Controller controller) {
    super(parent);
    this.mapping = mapping;
    this.handler = handler;
    this.method = method;
    this.controller = controller;
}
 
Example 23
Source Project: halo-docs   Source File: ParameterTranslation.java    License: Apache License 2.0 5 votes vote down vote up
public ParameterTranslation(SpringMVCTranslation parent, RequestMappingInfo mapping, HandlerMethod handler, Method method, Controller controller, Operation operation) {
    super(parent);
    this.mapping = mapping;
    this.handler = handler;
    this.method = method;
    this.controller = controller;
    this.operation = operation;
}
 
Example 24
@Override
public void afterPropertiesSet() {
    this.config = new RequestMappingInfo.BuilderConfiguration();
    this.config.setUrlPathHelper(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();
}
 
Example 25
Source Project: onetwo   Source File: PermissionHandlerMappingListener.java    License: Apache License 2.0 5 votes vote down vote up
private void setMenuUrlByRequestMappingInfo(Class<?> codeClass, IPermission perm, Entry<RequestMappingInfo, HandlerMethod> entry){
		IPermission menu = perm;

		Optional<RequestMethod> method = getFirstMethod(entry.getKey());
		if(method.isPresent() && RequestMethod.GET!=method.get()){
			return ;
		}
		
//		menu.setMethod(method);
		method.ifPresent(m->menu.setMethod(m.name()));
//		String url = entry.getKey().getPatternsCondition().getPatterns().iterator().next();
		String url = null;
		if(StringUtils.isNotBlank(menu.getUrl())){
			//如果自定义了,忽略自动解释
			url = menu.getUrl();
			menu.setUrl(url);
		}else{
			url = getFirstUrl(entry.getKey());
			if(!ExpressionFacotry.BRACE.isExpresstion(url)){
				menu.setUrl(url);
			}else{
				logger.info("url[{}] has brace, ignore.", url);
			}
		}
//		Iterator<RequestMethod> it = entry.getKey().getMethodsCondition().getMethods().iterator();

		/*if(it.hasNext()){
			//取第一个映射方法
			String method = entry.getKey().getMethodsCondition().getMethods().iterator().next().toString();
			menu.setMethod(method);
		}else{
			menu.setMethod(RequestMethod.GET.name());
		}*/
	}
 
Example 26
/**
 * Delegates to {@link #createRequestMappingInfo(RequestMapping, RequestCondition)},
 * supplying the appropriate custom {@link RequestCondition} depending on whether
 * the supplied {@code annotatedElement} is a class or method.
 * @see #getCustomTypeCondition(Class)
 * @see #getCustomMethodCondition(Method)
 */
@Nullable
private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) {
	RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);
	RequestCondition<?> condition = (element instanceof Class ?
			getCustomTypeCondition((Class<?>) element) : getCustomMethodCondition((Method) element));
	return (requestMapping != null ? createRequestMappingInfo(requestMapping, condition) : null);
}
 
Example 27
@Nullable
private RequestMappingInfo getApiVersionMappingInfo(Method method, Class<?> handlerType) {
	// url 上的版本,优先获取方法上的版本
	UrlVersion urlVersion = AnnotatedElementUtils.findMergedAnnotation(method, UrlVersion.class);
	// 再次尝试类上的版本
	if (urlVersion == null || StringUtil.isBlank(urlVersion.value())) {
		urlVersion = AnnotatedElementUtils.findMergedAnnotation(handlerType, UrlVersion.class);
	}
	// Media Types 版本信息
	ApiVersion apiVersion = AnnotatedElementUtils.findMergedAnnotation(method, ApiVersion.class);
	// 再次尝试类上的版本
	if (apiVersion == null || StringUtil.isBlank(apiVersion.value())) {
		apiVersion = AnnotatedElementUtils.findMergedAnnotation(handlerType, ApiVersion.class);
	}
	boolean nonUrlVersion = urlVersion == null || StringUtil.isBlank(urlVersion.value());
	boolean nonApiVersion = apiVersion == null || StringUtil.isBlank(apiVersion.value());
	// 先判断同时不纯在
	if (nonUrlVersion && nonApiVersion) {
		return null;
	}
	// 如果 header 版本不存在
	RequestMappingInfo.Builder mappingInfoBuilder = null;
	if (nonApiVersion) {
		mappingInfoBuilder = RequestMappingInfo.paths(urlVersion.value());
	} else {
		mappingInfoBuilder = RequestMappingInfo.paths(StringPool.EMPTY);
	}
	// 如果url版本不存在
	if (nonUrlVersion) {
		String vsersionMediaTypes = new BladeMediaType(apiVersion.value()).toString();
		mappingInfoBuilder.produces(vsersionMediaTypes);
	}
	return mappingInfoBuilder.build();
}
 
Example 28
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;
}
 
Example 29
private void updateConsumesCondition(RequestMappingInfo info, Method method) {
	ConsumesRequestCondition condition = info.getConsumesCondition();
	if (!condition.isEmpty()) {
		for (Parameter parameter : method.getParameters()) {
			MergedAnnotation<RequestBody> annot = MergedAnnotations.from(parameter).get(RequestBody.class);
			if (annot.isPresent()) {
				condition.setBodyRequired(annot.getBoolean("required"));
				break;
			}
		}
	}
}
 
Example 30
@Override
protected void handlerMethodsInitialized(Map<RequestMappingInfo, HandlerMethod> handlerMethods) {
	// 打印路由信息 spring boot 2.1 去掉了这个 日志的打印
	if (logger.isInfoEnabled()) {
		for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
			RequestMappingInfo mapping = entry.getKey();
			HandlerMethod handlerMethod = entry.getValue();
			logger.info("Mapped \"" + mapping + "\" onto " + handlerMethod);
		}
	}
	super.handlerMethodsInitialized(handlerMethods);
}