org.springframework.web.method.HandlerMethod Java Examples

The following examples show how to use org.springframework.web.method.HandlerMethod. 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
Source File: UifControllerHandlerInterceptorTest.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Builds instance of a handler method (using the controller) for the given method to call.
 *
 * @param methodToCall method on controller to build handler for
 * @return handler method instance
 */
protected HandlerMethod getHandlerMethod(String methodToCall) {
    Method method = null;

    for (Method controllerMethod : controller.getClass().getMethods()) {
        if (StringUtils.equals(controllerMethod.getName(), methodToCall)) {
            method = controllerMethod;
        }
    }

    if (method != null) {
        return new HandlerMethod(controller, method);
    }

    return null;
}
 
Example #2
Source File: IdempotencyInterceptor.java    From bird-java with MIT License 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (!(handler instanceof HandlerMethod)) return true;

    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Idempotency idempotency = handlerMethod.getMethodAnnotation(Idempotency.class);
    if (idempotency == null) return true;

    String token = request.getHeader(this.headerName);
    if (StringUtils.isBlank(token)) {
        logger.warn("幂等性接口:{},请求头中token为空.", request.getRequestURI());
        if (idempotency.force()) {
            response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "该操作已失效,请刷新后重试");
            return false;
        }
        return true;
    }
    if (!CacheHelper.getCache().del(WebConstant.Cache.IDEMPOTENCY_NAMESPACE + token)) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "该操作已提交");
        return false;
    }

    return true;
}
 
Example #3
Source File: UserAuthRestInterceptor.java    From sanshanblog with Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    // 配置该注解,说明进行用户拦截
    WantUserToken annotation = handlerMethod.getBeanType().getAnnotation(WantUserToken.class);
    if (annotation==null){
        annotation = handlerMethod.getMethodAnnotation(WantUserToken.class);
    }
    //判断在网关处鉴权
    String token = request.getHeader(userAuthConfig.getTokenHeader());
    if (StringUtils.isEmpty(token)) {
        if (annotation == null) {
            return super.preHandle(request, response, handler);
        }
    }
    //进行拦截
    IJWTInfo infoFromToken = userAuthUtil.getInfoFromToken(token);
    UserContextHandler.setUsername(infoFromToken.getUsername());
    UserContextHandler.setUserID(infoFromToken.getId());
    return super.preHandle(request, response, handler);
}
 
Example #4
Source File: CatnapResponseBodyHandlerInterceptor.java    From catnap with Apache License 2.0 6 votes vote down vote up
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
        throws Exception {
    HandlerMethod method = (HandlerMethod) handler;

    if (method.getMethodAnnotation(ResponseBody.class) == null) {
        CatnapResponseBody annotation = method.getMethodAnnotation(CatnapResponseBody.class);

        if (annotation != null) {
            String modelName = modelName(annotation, method);

            if (modelAndView != null) {
                //Transfer the model to a well known key so that we can retrieve it in the view.
                Object model = modelAndView.getModel().get(modelName);
                modelAndView.getModel().put(MODEL_NAME, model);
            }
        }
    }
}
 
Example #5
Source File: ContextInterceptor.java    From faster-framework-project with Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request,
                         HttpServletResponse response, Object handler) {
    setRequestContext(request);
    if (!(handler instanceof HandlerMethod)) {
        return true;
    }
    HandlerMethod handlerMethod = (HandlerMethod) handler;
    Method method = handlerMethod.getMethod();
    //判断当前请求是否为接口
    boolean hasResponseBody = method.isAnnotationPresent(ResponseBody.class);
    boolean hasRestController = handlerMethod.getBeanType().isAnnotationPresent(RestController.class);
    RequestContext requestContext = WebContextFacade.getRequestContext();
    requestContext.setApiRequest(hasResponseBody || hasRestController);
    WebContextFacade.setRequestContext(requestContext);
    return true;
}
 
Example #6
Source File: PathParametersSnippetTest.java    From spring-auto-restdocs with Apache License 2.0 6 votes vote down vote up
@Test
public void failOnUndocumentedParams() throws Exception {
    HandlerMethod handlerMethod = createHandlerMethod("addItem", Integer.class, String.class,
            int.class, String.class, Optional.class);
    initParameters(handlerMethod);

    thrown.expect(SnippetException.class);
    thrown.expectMessage(
            "Following path parameters were not documented: [id, subid, partId, yetAnotherId, optionalId]");

    new PathParametersSnippet().failOnUndocumentedParams(true).document(operationBuilder
            .attribute(HandlerMethod.class.getName(), handlerMethod)
            .attribute(JavadocReader.class.getName(), javadocReader)
            .attribute(ConstraintReader.class.getName(), constraintReader)
            .build());
}
 
Example #7
Source File: RequestResponseBodyMethodProcessorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test  // SPR-9964
public void resolveArgumentTypeVariable() throws Exception {
	Method method = MyParameterizedController.class.getMethod("handleDto", Identifiable.class);
	HandlerMethod handlerMethod = new HandlerMethod(new MySimpleParameterizedController(), method);
	MethodParameter methodParam = handlerMethod.getMethodParameters()[0];

	String content = "{\"name\" : \"Jad\"}";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);

	List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
	converters.add(new MappingJackson2HttpMessageConverter());
	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);

	SimpleBean result = (SimpleBean) processor.resolveArgument(methodParam, mavContainer, webRequest, binderFactory);

	assertNotNull(result);
	assertEquals("Jad", result.getName());
}
 
Example #8
Source File: UserInterceptorHandler.java    From youkefu with Apache License 2.0 6 votes vote down vote up
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
	boolean filter = false; 
    User user = (User) request.getSession(true).getAttribute(UKDataContext.USER_SESSION_NAME) ;
    if(handler instanceof HandlerMethod) {
     HandlerMethod  handlerMethod = (HandlerMethod ) handler ;
     Menu menu = handlerMethod.getMethod().getAnnotation(Menu.class) ;
     if(user != null || (menu!=null && menu.access()) || handlerMethod.getBean() instanceof BasicErrorController){
     	filter = true;
     }
     
     if(!filter){
     	response.sendRedirect("/login.html");
     }
    }else {
    	filter =true ;
    }
    return filter ; 
}
 
Example #9
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-13318
public void jacksonSubType() throws Exception {
	Method method = JacksonController.class.getMethod("handleSubType");
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodReturnType = handlerMethod.getReturnType();

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2HttpMessageConverter());
	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);

	Object returnValue = new JacksonController().handleSubType();
	processor.handleReturnValue(returnValue, methodReturnType, this.container, this.request);

	String content = this.servletResponse.getContentAsString();
	assertTrue(content.contains("\"id\":123"));
	assertTrue(content.contains("\"name\":\"foo\""));
}
 
Example #10
Source File: RequestMappingService.java    From api-mock-util with 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 #11
Source File: UploadInterceptor.java    From spring-boot-plus with Apache License 2.0 6 votes vote down vote up
@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果访问的不是控制器,则跳出,继续执行下一个拦截器
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 访问路径
        String url = request.getRequestURI();
        // 访问全路径
        String fullUrl = request.getRequestURL().toString();
        // 上传拦截器,业务处理代码
        log.debug("UploadInterceptor...");
        // 访问token,如果需要,可以设置参数,进行鉴权
//        String token = request.getParameter(JwtTokenUtil.getTokenName());
        return true;
    }
 
Example #12
Source File: OpenApiResource.java    From springdoc-openapi with 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 #13
Source File: ModelInitializerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void saveModelAttributeToSession() throws Exception {
	TestController controller = new TestController();
	InitBinderBindingContext context = getBindingContext(controller);

	Method method = ResolvableMethod.on(TestController.class).annotPresent(GetMapping.class).resolveMethod();
	HandlerMethod handlerMethod = new HandlerMethod(controller, method);
	this.modelInitializer.initModel(handlerMethod, context, this.exchange).block(Duration.ofMillis(5000));

	WebSession session = this.exchange.getSession().block(Duration.ZERO);
	assertNotNull(session);
	assertEquals(0, session.getAttributes().size());

	context.saveModel();
	assertEquals(1, session.getAttributes().size());
	assertEquals("Bean", ((TestBean) session.getRequiredAttribute("bean")).getName());
}
 
Example #14
Source File: ModelFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void sessionAttributeNotPresent() throws Exception {
	ModelFactory modelFactory = new ModelFactory(null, null, this.attributeHandler);
	HandlerMethod handlerMethod = createHandlerMethod("handleSessionAttr", String.class);
	try {
		modelFactory.initModel(this.webRequest, this.mavContainer, handlerMethod);
		fail("Expected HttpSessionRequiredException");
	}
	catch (HttpSessionRequiredException ex) {
		// expected
	}

	// Now add attribute and try again
	this.attributeStore.storeAttribute(this.webRequest, "sessionAttr", "sessionAttrValue");

	modelFactory.initModel(this.webRequest, this.mavContainer, handlerMethod);
	assertEquals("sessionAttrValue", this.mavContainer.getModel().get("sessionAttr"));
}
 
Example #15
Source File: RequestMappingHandlerMapping.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #16
Source File: RepeatSubmitInterceptor.java    From RuoYi-Vue with MIT License 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
{
    if (handler instanceof HandlerMethod)
    {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
        if (annotation != null)
        {
            if (this.isRepeatSubmit(request))
            {
                AjaxResult ajaxResult = AjaxResult.error("不允许重复提交,请稍后再试");
                ServletUtils.renderString(response, JSONObject.toJSONString(ajaxResult));
                return false;
            }
        }
        return true;
    }
    else
    {
        return super.preHandle(request, response, handler);
    }
}
 
Example #17
Source File: TraceWebFilter.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
private void addClassNameTag(Object handler, Span span) {
	if (handler == null) {
		return;
	}
	String className;
	if (handler instanceof HandlerMethod) {
		className = ((HandlerMethod) handler).getBeanType().getSimpleName();
	}
	else {
		className = handler.getClass().getSimpleName();
	}
	if (log.isDebugEnabled()) {
		log.debug("Adding a class tag with value [" + className
				+ "] to a span " + span);
	}
	span.tag(MVC_CONTROLLER_CLASS_KEY, className);
}
 
Example #18
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-12501
public void resolveHttpEntityArgumentWithJacksonJsonView() throws Exception {
	String content = "{\"withView1\" : \"with\", \"withView2\" : \"with\", \"withoutView\" : \"without\"}";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);

	Method method = JacksonController.class.getMethod("handleHttpEntity", HttpEntity.class);
	HandlerMethod handlerMethod = new HandlerMethod(new JacksonController(), method);
	MethodParameter methodParameter = handlerMethod.getMethodParameters()[0];

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2HttpMessageConverter());

	HttpEntityMethodProcessor processor = new HttpEntityMethodProcessor(
			converters, null, Collections.singletonList(new JsonViewRequestBodyAdvice()));

	@SuppressWarnings("unchecked")
	HttpEntity<JacksonViewBean> result = (HttpEntity<JacksonViewBean>)
			processor.resolveArgument( methodParameter, this.container, this.request, this.factory);

	assertNotNull(result);
	assertNotNull(result.getBody());
	assertEquals("with", result.getBody().getWithView1());
	assertNull(result.getBody().getWithView2());
	assertNull(result.getBody().getWithoutView());
}
 
Example #19
Source File: PrintingResultHandler.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Print the handler.
 */
protected void printHandler(@Nullable Object handler, @Nullable HandlerInterceptor[] interceptors)
		throws Exception {

	if (handler == null) {
		this.printer.printValue("Type", null);
	}
	else {
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			this.printer.printValue("Type", handlerMethod.getBeanType().getName());
			this.printer.printValue("Method", handlerMethod);
		}
		else {
			this.printer.printValue("Type", handler.getClass().getName());
		}
	}
}
 
Example #20
Source File: SpringRepositoryRestResourceProvider.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
/**
 * Find search resource mappings.
 *
 * @param openAPI the open api
 * @param routerOperationList the router operation list
 * @param handlerMappingList the handler mapping list
 * @param domainType the domain type
 * @param resourceMetadata the resource metadata
 */
private void findSearchResourceMappings(OpenAPI openAPI, List<RouterOperation> routerOperationList, List<HandlerMapping> handlerMappingList, Class<?> domainType, ResourceMetadata resourceMetadata) {
	for (HandlerMapping handlerMapping : handlerMappingList) {
		if (handlerMapping instanceof RepositoryRestHandlerMapping) {
			RepositoryRestHandlerMapping repositoryRestHandlerMapping = (RepositoryRestHandlerMapping) handlerMapping;
			Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = repositoryRestHandlerMapping.getHandlerMethods();
			Map<RequestMappingInfo, HandlerMethod> handlerMethodMapFiltered = handlerMethodMap.entrySet().stream()
					.filter(requestMappingInfoHandlerMethodEntry -> REPOSITORY_SERACH_CONTROLLER.equals(requestMappingInfoHandlerMethodEntry
							.getValue().getBeanType().getName()))
					.filter(controller -> !AbstractOpenApiResource.isHiddenRestControllers(controller.getValue().getBeanType()))
					.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a1, a2) -> a1));
			ResourceMetadata metadata = associations.getMetadataFor(domainType);
			SearchResourceMappings searchResourceMappings = metadata.getSearchResourceMappings();
			if (searchResourceMappings.isExported()) {
				findSearchControllers(routerOperationList, handlerMethodMapFiltered, resourceMetadata, domainType, openAPI, searchResourceMappings);
			}
		}
	}
}
 
Example #21
Source File: RequestMappingInfoHandlerMappingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void testHttpOptions(String requestURI, Set<HttpMethod> allowedMethods) {
	ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.options(requestURI));
	HandlerMethod handlerMethod = (HandlerMethod) this.handlerMapping.getHandler(exchange).block();

	BindingContext bindingContext = new BindingContext();
	InvocableHandlerMethod invocable = new InvocableHandlerMethod(handlerMethod);
	Mono<HandlerResult> mono = invocable.invoke(exchange, bindingContext);

	HandlerResult result = mono.block();
	assertNotNull(result);

	Object value = result.getReturnValue();
	assertNotNull(value);
	assertEquals(HttpHeaders.class, value.getClass());
	assertEquals(allowedMethods, ((HttpHeaders) value).getAllow());
}
 
Example #22
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-11225
public void resolveArgumentTypeVariableWithNonGenericConverter() throws Exception {
	Method method = MyParameterizedController.class.getMethod("handleDto", Identifiable.class);
	HandlerMethod handlerMethod = new HandlerMethod(new MySimpleParameterizedController(), method);
	MethodParameter methodParam = handlerMethod.getMethodParameters()[0];

	String content = "{\"name\" : \"Jad\"}";
	this.servletRequest.setContent(content.getBytes("UTF-8"));
	this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);

	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	HttpMessageConverter<Object> target = new MappingJackson2HttpMessageConverter();
	HttpMessageConverter<?> proxy = ProxyFactory.getProxy(HttpMessageConverter.class, new SingletonTargetSource(target));
	converters.add(proxy);
	RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);

	SimpleBean result = (SimpleBean) processor.resolveArgument(methodParam, container, request, factory);

	assertNotNull(result);
	assertEquals("Jad", result.getName());
}
 
Example #23
Source File: RequestMappingHandlerAdapterIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void handleAndValidateRequestBody() throws Exception {
	Class<?>[] parameterTypes = new Class<?>[] {TestBean.class, Errors.class};

	request.addHeader("Content-Type", "text/plain; charset=utf-8");
	request.setContent("Hello Server".getBytes("UTF-8"));

	HandlerMethod handlerMethod = handlerMethod("handleAndValidateRequestBody", parameterTypes);

	ModelAndView mav = handlerAdapter.handle(request, response, handlerMethod);

	assertNull(mav);
	assertEquals("Error count [1]", new String(response.getContentAsByteArray(), "UTF-8"));
	assertEquals(HttpStatus.ACCEPTED.value(), response.getStatus());
}
 
Example #24
Source File: BeforeTtrackingHandler.java    From SO with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public Flow handle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler, String[] flags) throws Exception {

    // session id
    String sessionId = IdUtils.createRandomUUID();
    TrackingEntity tracking = new TrackingEntity();
        tracking.setSessionId(sessionId);
        tracking.setUri(request.getRequestURI());
        tracking.setMethod(request.getMethod());
        tracking.setRemoteAddr(request.getRemoteAddr());
        tracking.setRemoteHost(request.getRemoteHost());
        tracking.setProcess(getClass().getSimpleName());
        tracking.setProcessId(request.getRequestURI());
        tracking.setProcessName("API요청");

    // tracking
    DefaultProducerHandler trackingHandler = new DefaultProducerHandler(0, "tracking");
    trackingHandler.send(tracking);
    trackingHandler.close();

    // clear request information
    tracking.clearRequestInfomation();

    // set session
    HttpSession session = request.getSession();
    session.setAttribute("tracking", tracking);

    //or return Flow.HALT to halt this request and prevent execution of the context
    //you may also wish to redirect to a login page here
    return Flow.CONTINUE;
}
 
Example #25
Source File: MenuServiceImpl.java    From FEBS-Security with Apache License 2.0 5 votes vote down vote up
@Override
public List<Map<String, String>> getAllUrl(String p1) {
    RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
    //获取 url与类和方法的对应信息
    Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
    List<Map<String, String>> urlList = new ArrayList<>();
    for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : map.entrySet()) {
        RequestMappingInfo info = entry.getKey();
        HandlerMethod handlerMethod = map.get(info);
        PreAuthorize permissions = handlerMethod.getMethodAnnotation(PreAuthorize.class);
        String perms = "";
        if (null != permissions) {
            String value = permissions.value();
            value = StringUtils.substringBetween(value, "hasAuthority(", ")");
            perms = StringUtils.join(value, ",");
        }
        Set<String> patterns = info.getPatternsCondition().getPatterns();
        for (String url : patterns) {
            Map<String, String> urlMap = new HashMap<>();
            urlMap.put("url", url.replaceFirst("\\/", ""));
            urlMap.put("perms", perms);
            urlList.add(urlMap);
        }
    }
    return urlList;

}
 
Example #26
Source File: AbstractHandlerMethodMapping.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Look up the best-matching handler method for the current request.
 * If multiple matches are found, the best match is selected.
 * @param exchange the current exchange
 * @return the best-matching handler method, or {@code null} if no match
 * @see #handleMatch
 * @see #handleNoMatch
 */
@Nullable
protected HandlerMethod lookupHandlerMethod(ServerWebExchange exchange) throws Exception {
	List<Match> matches = new ArrayList<>();
	addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, exchange);

	if (!matches.isEmpty()) {
		Comparator<Match> comparator = new MatchComparator(getMappingComparator(exchange));
		matches.sort(comparator);
		Match bestMatch = matches.get(0);
		if (matches.size() > 1) {
			if (logger.isTraceEnabled()) {
				logger.trace(exchange.getLogPrefix() + matches.size() + " matching mappings: " + matches);
			}
			if (CorsUtils.isPreFlightRequest(exchange.getRequest())) {
				return PREFLIGHT_AMBIGUOUS_MATCH;
			}
			Match secondBestMatch = matches.get(1);
			if (comparator.compare(bestMatch, secondBestMatch) == 0) {
				Method m1 = bestMatch.handlerMethod.getMethod();
				Method m2 = secondBestMatch.handlerMethod.getMethod();
				RequestPath path = exchange.getRequest().getPath();
				throw new IllegalStateException(
						"Ambiguous handler methods mapped for '" + path + "': {" + m1 + ", " + m2 + "}");
			}
		}
		handleMatch(bestMatch.mapping, bestMatch.handlerMethod, exchange);
		return bestMatch.handlerMethod;
	}
	else {
		return handleNoMatch(this.mappingRegistry.getMappings().keySet(), exchange);
	}
}
 
Example #27
Source File: JacksonResponseFieldSnippetTest.java    From spring-auto-restdocs with Apache License 2.0 5 votes vote down vote up
@Test
public void resourcesResponse() throws Exception {
    HandlerMethod handlerMethod = createHandlerMethod("itemResources");

    new JacksonResponseFieldSnippet().document(operationBuilder
            .attribute(HandlerMethod.class.getName(), handlerMethod)
            .attribute(ObjectMapper.class.getName(), mapper)
            .attribute(JavadocReader.class.getName(), javadocReader)
            .attribute(ConstraintReader.class.getName(), constraintReader)
            .build());

    assertThat(this.generatedSnippets.snippet(AUTO_RESPONSE_FIELDS))
            .isEqualTo("Body contains embedded resources.");
}
 
Example #28
Source File: BladeRequestMappingHandlerMapping.java    From blade-tool with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example #29
Source File: RequestMappingInfoHandlerMappingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void testHttpOptions(String requestURI, String allowHeader) throws Exception {
	MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", requestURI);
	HandlerMethod handlerMethod = getHandler(request);

	ServletWebRequest webRequest = new ServletWebRequest(request);
	ModelAndViewContainer mavContainer = new ModelAndViewContainer();
	Object result = new InvocableHandlerMethod(handlerMethod).invokeForRequest(webRequest, mavContainer);

	assertNotNull(result);
	assertEquals(HttpHeaders.class, result.getClass());
	assertEquals(allowHeader, ((HttpHeaders) result).getFirst("Allow"));
}
 
Example #30
Source File: AdminPermissionInterceptor.java    From spring-boot-start-current with Apache License 2.0 5 votes vote down vote up
private < T extends Annotation > T getHandlerAnnotation ( HandlerMethod handlerMethod ,
                                                          Class< T > clazz ) {
    T annotation = handlerMethod.getMethodAnnotation( clazz );
    if ( Objects.nonNull( annotation ) ) {
        return annotation;
    }
    return handlerMethod.getBeanType().getAnnotation( clazz );
}