org.springframework.boot.test.context.FilteredClassLoader#org.springframework.web.reactive.HandlerMapping源码实例Demo

下面列出了org.springframework.boot.test.context.FilteredClassLoader#org.springframework.web.reactive.HandlerMapping 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: spring-analysis-note   文件: ResourceWebHandler.java
protected Mono<Resource> getResource(ServerWebExchange exchange) {
	String name = HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE;
	PathContainer pathWithinHandler = exchange.getRequiredAttribute(name);

	String path = processPath(pathWithinHandler.value());
	if (!StringUtils.hasText(path) || isInvalidPath(path)) {
		return Mono.empty();
	}
	if (isInvalidEncodedPath(path)) {
		return Mono.empty();
	}

	Assert.state(this.resolverChain != null, "ResourceResolverChain not initialized");
	Assert.state(this.transformerChain != null, "ResourceTransformerChain not initialized");

	return this.resolverChain.resolveResource(exchange, path, getLocations())
			.flatMap(resource -> this.transformerChain.transform(exchange, resource));
}
 
源代码2 项目: spring-cloud-sleuth   文件: TraceWebFilter.java
private void terminateSpan(@Nullable Throwable t) {
	Object attribute = this.exchange
			.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE);
	addClassMethodTag(attribute, this.span);
	addClassNameTag(attribute, this.span);
	Object pattern = this.exchange
			.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
	String httpRoute = pattern != null ? pattern.toString() : "";
	addResponseTagsForSpanWithoutParent(this.exchange,
			this.exchange.getResponse(), this.span);
	WrappedResponse response = new WrappedResponse(
			this.exchange.getResponse(),
			this.exchange.getRequest().getMethodValue(), httpRoute);
	this.handler.handleSend(response, t, this.span);
	if (log.isDebugEnabled()) {
		log.debug("Handled send of " + this.span);
	}
}
 
@Test
@SuppressWarnings("resource")
public void handlerMappingJavaConfig() throws Exception {
	AnnotationConfigApplicationContext wac = new AnnotationConfigApplicationContext();
	wac.register(WebConfig.class);
	wac.refresh();

	HandlerMapping handlerMapping = (HandlerMapping) wac.getBean("handlerMapping");
	Object mainController = wac.getBean("mainController");
	Object otherController = wac.getBean("otherController");

	testUrl("/welcome.html", mainController, handlerMapping, "");
	testUrl("/welcome.x", otherController, handlerMapping, "welcome.x");
	testUrl("/welcome/", otherController, handlerMapping, "welcome");
	testUrl("/show.html", mainController, handlerMapping, "");
	testUrl("/bookseats.html", mainController, handlerMapping, "");
}
 
private void testUrl(String url, Object bean, HandlerMapping handlerMapping, String pathWithinMapping) {
	MockServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, URI.create(url)).build();
	ServerWebExchange exchange = MockServerWebExchange.from(request);
	Object actual = handlerMapping.getHandler(exchange).block();
	if (bean != null) {
		assertNotNull(actual);
		assertSame(bean, actual);
		//noinspection OptionalGetWithoutIsPresent
		PathContainer path = exchange.getAttribute(PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
		assertNotNull(path);
		assertEquals(pathWithinMapping, path.value());
	}
	else {
		assertNull(actual);
	}
}
 
@Test  // SPR-9098
public void handleMatchUriTemplateVariablesDecode() {
	RequestMappingInfo key = paths("/{group}/{identifier}").build();
	URI url = URI.create("/group/a%2Fb");
	ServerWebExchange exchange = MockServerWebExchange.from(method(HttpMethod.GET, url));

	this.handlerMapping.handleMatch(key, handlerMethod, exchange);

	String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
	@SuppressWarnings("unchecked")
	Map<String, String> uriVariables = (Map<String, String>) exchange.getAttributes().get(name);

	assertNotNull(uriVariables);
	assertEquals("group", uriVariables.get("group"));
	assertEquals("a/b", uriVariables.get("identifier"));
}
 
@Bean
public HandlerMapping webSocketMessagingHandlerMapping(MessagingManager messagingManager,
                                       UserTokenManager userTokenManager,
                                       ReactiveAuthenticationManager authenticationManager) {


    WebSocketMessagingHandler messagingHandler=new WebSocketMessagingHandler(
        messagingManager,
        userTokenManager,
        authenticationManager
    );
    final Map<String, WebSocketHandler> map = new HashMap<>(1);
    map.put("/messaging/**", messagingHandler);

    final SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
    mapping.setOrder(Ordered.HIGHEST_PRECEDENCE);
    mapping.setUrlMap(map);
    return mapping;
}
 
protected Mono<Resource> getResource(ServerWebExchange exchange) {
	String name = HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE;
	PathContainer pathWithinHandler = exchange.getRequiredAttribute(name);

	String path = processPath(pathWithinHandler.value());
	if (!StringUtils.hasText(path) || isInvalidPath(path)) {
		return Mono.empty();
	}
	if (isInvalidEncodedPath(path)) {
		return Mono.empty();
	}

	Assert.state(this.resolverChain != null, "ResourceResolverChain not initialized");
	Assert.state(this.transformerChain != null, "ResourceTransformerChain not initialized");

	return this.resolverChain.resolveResource(exchange, path, getLocations())
			.flatMap(resource -> this.transformerChain.transform(exchange, resource));
}
 
@Test
@SuppressWarnings("resource")
public void handlerMappingJavaConfig() throws Exception {
	AnnotationConfigApplicationContext wac = new AnnotationConfigApplicationContext();
	wac.register(WebConfig.class);
	wac.refresh();

	HandlerMapping handlerMapping = (HandlerMapping) wac.getBean("handlerMapping");
	Object mainController = wac.getBean("mainController");
	Object otherController = wac.getBean("otherController");

	testUrl("/welcome.html", mainController, handlerMapping, "");
	testUrl("/welcome.x", otherController, handlerMapping, "welcome.x");
	testUrl("/welcome/", otherController, handlerMapping, "welcome");
	testUrl("/show.html", mainController, handlerMapping, "");
	testUrl("/bookseats.html", mainController, handlerMapping, "");
}
 
private void testUrl(String url, Object bean, HandlerMapping handlerMapping, String pathWithinMapping) {
	MockServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, URI.create(url)).build();
	ServerWebExchange exchange = MockServerWebExchange.from(request);
	Object actual = handlerMapping.getHandler(exchange).block();
	if (bean != null) {
		assertNotNull(actual);
		assertSame(bean, actual);
		//noinspection OptionalGetWithoutIsPresent
		PathContainer path = exchange.getAttribute(PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
		assertNotNull(path);
		assertEquals(pathWithinMapping, path.value());
	}
	else {
		assertNull(actual);
	}
}
 
@Test  // SPR-9098
public void handleMatchUriTemplateVariablesDecode() {
	RequestMappingInfo key = paths("/{group}/{identifier}").build();
	URI url = URI.create("/group/a%2Fb");
	ServerWebExchange exchange = MockServerWebExchange.from(method(HttpMethod.GET, url));

	this.handlerMapping.handleMatch(key, handlerMethod, exchange);

	String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
	@SuppressWarnings("unchecked")
	Map<String, String> uriVariables = (Map<String, String>) exchange.getAttributes().get(name);

	assertNotNull(uriVariables);
	assertEquals("group", uriVariables.get("group"));
	assertEquals("a/b", uriVariables.get("identifier"));
}
 
源代码11 项目: vertx-spring-boot   文件: WebSocketIT.java
@Bean
public HandlerMapping handlerMapping() {
    Map<String, WebSocketHandler> map = new HashMap<>();
    map.put("/echo", this::echoHandler);
    map.put("/sink", this::sinkHandler);
    map.put("/double-producer", this::doubleProducerHandler);
    map.put("/close", this::closeHandler);

    SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
    mapping.setUrlMap(map);
    mapping.setOrder(-1);

    CorsConfiguration cors = new CorsConfiguration();
    cors.addAllowedOrigin("http://snowdrop.dev");
    mapping.setCorsConfigurations(Collections.singletonMap("/sink", cors));

    return mapping;
}
 
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
                          Object ret) throws Throwable {
    ServerWebExchange exchange = (ServerWebExchange) allArguments[0];
    AbstractSpan span = (AbstractSpan) objInst.getSkyWalkingDynamicField();

    return ((Mono) ret).doFinally(s -> {
        try {
            Object pathPattern = exchange.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
            if (pathPattern != null) {
                span.setOperationName(((PathPattern) pathPattern).getPatternString());
            }
            HttpStatus httpStatus = exchange.getResponse().getStatusCode();
            // fix webflux-2.0.0-2.1.0 version have bug. httpStatus is null. not support
            if (httpStatus != null) {
                Tags.STATUS_CODE.set(span, Integer.toString(httpStatus.value()));
                if (httpStatus.isError()) {
                    span.errorOccurred();
                }
            }
        } finally {
            span.asyncFinish();
        }
    });

}
 
@Bean
HandlerMapping webSocketMapping(CommentService commentService) {
	Map<String, WebSocketHandler> urlMap = new HashMap<>();
	urlMap.put("/topic/comments.new", commentService);

	Map<String, CorsConfiguration> corsConfigurationMap =
		new HashMap<>();
	CorsConfiguration corsConfiguration = new CorsConfiguration();
	corsConfiguration.addAllowedOrigin("http://localhost:8080");
	corsConfigurationMap.put(
		"/topic/comments.new", corsConfiguration);

	SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
	mapping.setOrder(10);
	mapping.setUrlMap(urlMap);
	mapping.setCorsConfigurations(corsConfigurationMap);

	return mapping;
}
 
@Bean
HandlerMapping webSocketMapping(CommentService commentService,
								InboundChatService inboundChatService,
								OutboundChatService outboundChatService) {
	SimpleUrlHandlerMapping mapping =
		configureUrlMappings(commentService, inboundChatService, outboundChatService);

	Map<String, CorsConfiguration> corsConfigurationMap = new HashMap<>();
	CorsConfiguration corsConfiguration = new CorsConfiguration();
	corsConfiguration.addAllowedOrigin(chatConfigProperties.getOrigin());

	mapping.getUrlMap().keySet().forEach(route ->
		corsConfigurationMap.put(route, corsConfiguration)
	);

	mapping.setCorsConfigurations(corsConfigurationMap);

	return mapping;
}
 
@Nullable
@Override
public Object resolveArgumentValue(MethodParameter parameter, BindingContext bindingContext,
		ServerWebExchange exchange) {

	Map<String, MultiValueMap<String, String>> matrixVariables =
			exchange.getAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE);

	if (CollectionUtils.isEmpty(matrixVariables)) {
		return Collections.emptyMap();
	}

	MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
	MatrixVariable annotation = parameter.getParameterAnnotation(MatrixVariable.class);
	Assert.state(annotation != null, "No MatrixVariable annotation");
	String pathVariable = annotation.pathVar();

	if (!pathVariable.equals(ValueConstants.DEFAULT_NONE)) {
		MultiValueMap<String, String> mapForPathVariable = matrixVariables.get(pathVariable);
		if (mapForPathVariable == null) {
			return Collections.emptyMap();
		}
		map.putAll(mapForPathVariable);
	}
	else {
		for (MultiValueMap<String, String> vars : matrixVariables.values()) {
			vars.forEach((name, values) -> {
				for (String value : values) {
					map.add(name, value);
				}
			});
		}
	}

	return (isSingleValueMap(parameter) ? map.toSingleValueMap() : map);
}
 
@Override
public Object resolveArgumentValue(
		MethodParameter methodParameter, BindingContext context, ServerWebExchange exchange) {

	String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
	return exchange.getAttributeOrDefault(name, Collections.emptyMap());
}
 
源代码17 项目: tools-journey   文件: WebSocketConfiguration.java
@Autowired
@Bean
public HandlerMapping webSocketMapping(final EchoHandler echoHandler) {
    final Map<String, WebSocketHandler> map = new HashMap<>(1);
    map.put("/objectecho", echoHandler);

    final SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
    mapping.setOrder(Ordered.HIGHEST_PRECEDENCE);
    mapping.setUrlMap(map);
    return mapping;
}
 
@Bean
public HandlerMapping handlerMapping() {
	Map<String, WebSocketHandler> map = new HashMap<>();
	map.put("/echo", new EchoWebSocketHandler());
	map.put("/sub-protocol", new SubProtocolWebSocketHandler());
	map.put("/custom-header", new CustomHeaderHandler());
	map.put("/close", new SessionClosingHandler());

	SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
	mapping.setUrlMap(map);
	return mapping;
}
 
@Test
@SuppressWarnings("resource")
public void handlerMappingXmlConfig() throws Exception {
	ClassPathXmlApplicationContext wac = new ClassPathXmlApplicationContext("map.xml", getClass());
	wac.refresh();

	HandlerMapping handlerMapping = wac.getBean("mapping", HandlerMapping.class);
	Object mainController = wac.getBean("mainController");

	testUrl("/pathmatchingTest.html", mainController, handlerMapping, "pathmatchingTest.html");
	testUrl("welcome.html", null, handlerMapping, null);
	testUrl("/pathmatchingAA.html", mainController, handlerMapping, "pathmatchingAA.html");
	testUrl("/pathmatchingA.html", null, handlerMapping, null);
	testUrl("/administrator/pathmatching.html", mainController, handlerMapping, "");
	testUrl("/administrator/test/pathmatching.html", mainController, handlerMapping, "test/pathmatching.html");
	testUrl("/administratort/pathmatching.html", null, handlerMapping, null);
	testUrl("/administrator/another/bla.xml", mainController, handlerMapping, "");
	testUrl("/administrator/another/bla.gif", null, handlerMapping, null);
	testUrl("/administrator/test/testlastbit", mainController, handlerMapping, "test/testlastbit");
	testUrl("/administrator/test/testla", null, handlerMapping, null);
	testUrl("/administrator/testing/longer/bla", mainController, handlerMapping, "bla");
	testUrl("/administrator/testing/longer2/notmatching/notmatching", null, handlerMapping, null);
	testUrl("/shortpattern/testing/toolong", null, handlerMapping, null);
	testUrl("/XXpathXXmatching.html", mainController, handlerMapping, "XXpathXXmatching.html");
	testUrl("/pathXXmatching.html", mainController, handlerMapping, "pathXXmatching.html");
	testUrl("/XpathXXmatching.html", null, handlerMapping, null);
	testUrl("/XXpathmatching.html", null, handlerMapping, null);
	testUrl("/show12.html", mainController, handlerMapping, "show12.html");
	testUrl("/show123.html", mainController, handlerMapping, "");
	testUrl("/show1.html", mainController, handlerMapping, "show1.html");
	testUrl("/reallyGood-test-is-this.jpeg", mainController, handlerMapping, "reallyGood-test-is-this.jpeg");
	testUrl("/reallyGood-tst-is-this.jpeg", null, handlerMapping, null);
	testUrl("/testing/test.jpeg", mainController, handlerMapping, "testing/test.jpeg");
	testUrl("/testing/test.jpg", null, handlerMapping, null);
	testUrl("/anotherTest", mainController, handlerMapping, "anotherTest");
	testUrl("/stillAnotherTest", null, handlerMapping, null);
	testUrl("outofpattern*ye", null, handlerMapping, null);
}
 
源代码20 项目: spring-analysis-note   文件: RedirectViewTests.java
@Test
public void expandUriTemplateVariablesFromExchangeAttribute() {
	String url = "https://url.somewhere.com?foo={foo}";
	Map<String, String> attributes = Collections.singletonMap("foo", "bar");
	this.exchange.getAttributes().put(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, attributes);
	RedirectView view = new RedirectView(url);
	view.render(new HashMap<>(), MediaType.TEXT_HTML, exchange).block();
	assertEquals(URI.create("https://url.somewhere.com?foo=bar"), this.exchange.getResponse().getHeaders().getLocation());
}
 
@Test
public void producibleMediaTypesRequestAttribute() throws Exception {
	MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/path"));
	exchange.getAttributes().put(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, Collections.singleton(IMAGE_GIF));

	List<MediaType> mediaTypes = Arrays.asList(IMAGE_JPEG, IMAGE_GIF, IMAGE_PNG);
	MediaType actual = resultHandler.selectMediaType(exchange, () -> mediaTypes);

	assertEquals(IMAGE_GIF, actual);
}
 
@SuppressWarnings("unchecked")
private MultiValueMap<String, String> getVariablesFor(String pathVarName) {
	Map<String, MultiValueMap<String, String>> matrixVariables =
			this.exchange.getAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE);

	MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
	matrixVariables.put(pathVarName, params);
	return params;
}
 
@SuppressWarnings("unchecked")
private MultiValueMap<String, String> getMatrixVariables(String pathVarName) {
	Map<String, MultiValueMap<String, String>> matrixVariables =
			this.exchange.getAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE);

	MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
	matrixVariables.put(pathVarName, params);

	return params;
}
 
@Test
public void resolveArgument() {
	Map<String, String> uriTemplateVars = new HashMap<>();
	uriTemplateVars.put("name", "value");
	this.exchange.getAttributes().put(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars);

	BindingContext bindingContext = new BindingContext();
	Mono<Object> mono = this.resolver.resolveArgument(this.paramNamedString, bindingContext, this.exchange);
	Object result = mono.block();
	assertEquals("value", result);
}
 
@Test
public void resolveArgumentNotRequired() {
	Map<String, String> uriTemplateVars = new HashMap<>();
	uriTemplateVars.put("name", "value");
	this.exchange.getAttributes().put(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars);

	BindingContext bindingContext = new BindingContext();
	Mono<Object> mono = this.resolver.resolveArgument(this.paramNotRequired, bindingContext, this.exchange);
	Object result = mono.block();
	assertEquals("value", result);
}
 
@Test
public void resolveArgumentWrappedAsOptional() {
	Map<String, String> uriTemplateVars = new HashMap<>();
	uriTemplateVars.put("name", "value");
	this.exchange.getAttributes().put(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars);

	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultFormattingConversionService());
	BindingContext bindingContext = new BindingContext(initializer);

	Mono<Object> mono = this.resolver.resolveArgument(this.paramOptional, bindingContext, this.exchange);
	Object result = mono.block();
	assertEquals(Optional.of("value"), result);
}
 
@Test
public void resolveArgument() throws Exception {
	Map<String, String> uriTemplateVars = new HashMap<>();
	uriTemplateVars.put("name1", "value1");
	uriTemplateVars.put("name2", "value2");
	this.exchange.getAttributes().put(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars);

	Mono<Object> mono = this.resolver.resolveArgument(this.paramMap, new BindingContext(), this.exchange);
	Object result = mono.block();

	assertEquals(uriTemplateVars, result);
}
 
@Test
public void getHandlerProducibleMediaTypesAttribute() {
	ServerWebExchange exchange = MockServerWebExchange.from(get("/content").accept(MediaType.APPLICATION_XML));
	this.handlerMapping.getHandler(exchange).block();

	String name = HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE;
	assertEquals(Collections.singleton(MediaType.APPLICATION_XML), exchange.getAttributes().get(name));

	exchange = MockServerWebExchange.from(get("/content").accept(MediaType.APPLICATION_JSON));
	this.handlerMapping.getHandler(exchange).block();

	assertNull("Negated expression shouldn't be listed as producible type",
			exchange.getAttributes().get(name));
}
 
@Test
@SuppressWarnings("unchecked")
public void handleMatchUriTemplateVariables() {
	ServerWebExchange exchange = MockServerWebExchange.from(get("/1/2"));

	RequestMappingInfo key = paths("/{path1}/{path2}").build();
	this.handlerMapping.handleMatch(key, handlerMethod, exchange);

	String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
	Map<String, String> uriVariables = (Map<String, String>) exchange.getAttributes().get(name);

	assertNotNull(uriVariables);
	assertEquals("1", uriVariables.get("path1"));
	assertEquals("2", uriVariables.get("path2"));
}
 
@Bean
public HandlerMapping handlerMapping() {
	Map<String, WebSocketHandler> map = new HashMap<>();
	map.put("/echo", new EchoWebSocketHandler());
	map.put("/echoForHttp", new EchoWebSocketHandler());
	map.put("/sub-protocol", new SubProtocolWebSocketHandler());
	map.put("/custom-header", new CustomHeaderHandler());
	map.put("/close", new SessionClosingHandler());

	SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
	mapping.setUrlMap(map);
	return mapping;
}