Java Code Examples for org.springframework.web.reactive.HandlerMapping

The following examples show how to use org.springframework.web.reactive.HandlerMapping. 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
Source Project: spring-analysis-note   Source File: ResourceWebHandler.java    License: MIT License 6 votes vote down vote up
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));
}
 
Example 2
Source Project: spring-cloud-sleuth   Source File: TraceWebFilter.java    License: Apache License 2.0 6 votes vote down vote up
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);
	}
}
 
Example 3
@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, "");
}
 
Example 4
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);
	}
}
 
Example 5
@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"));
}
 
Example 6
@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;
}
 
Example 7
Source Project: java-technology-stack   Source File: ResourceWebHandler.java    License: MIT License 6 votes vote down vote up
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));
}
 
Example 8
@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, "");
}
 
Example 9
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);
	}
}
 
Example 10
@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"));
}
 
Example 11
Source Project: vertx-spring-boot   Source File: WebSocketIT.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 12
@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();
        }
    });

}
 
Example 13
@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;
}
 
Example 14
@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;
}
 
Example 15
@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);
}
 
Example 16
@Override
public Object resolveArgumentValue(
		MethodParameter methodParameter, BindingContext context, ServerWebExchange exchange) {

	String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
	return exchange.getAttributeOrDefault(name, Collections.emptyMap());
}
 
Example 17
Source Project: tools-journey   Source File: WebSocketConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 18
Source Project: spring-analysis-note   Source File: WebSocketIntegrationTests.java    License: MIT License 5 votes vote down vote up
@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;
}
 
Example 19
@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);
}
 
Example 20
Source Project: spring-analysis-note   Source File: RedirectViewTests.java    License: MIT License 5 votes vote down vote up
@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());
}
 
Example 21
Source Project: spring-analysis-note   Source File: HandlerResultHandlerTests.java    License: MIT License 5 votes vote down vote up
@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);
}
 
Example 22
@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;
}
 
Example 23
@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;
}
 
Example 24
@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);
}
 
Example 25
@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);
}
 
Example 26
@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);
}
 
Example 27
@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);
}
 
Example 28
@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));
}
 
Example 29
@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"));
}
 
Example 30
@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;
}