Java Code Examples for org.springframework.web.server.ServerWebExchange#getRequiredAttribute()

The following examples show how to use org.springframework.web.server.ServerWebExchange#getRequiredAttribute() . 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: ReactiveLoadBalancerClientFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void unencodedParameters() {
	URI url = URI.create("http://localhost/get?a=b&c=d[]");

	MockServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, url)
			.build();

	URI lbUrl = URI.create("lb://service1?a=b&c=d[]");

	// prove that it is unencoded
	assertThat(lbUrl.getRawQuery()).isEqualTo("a=b&c=d[]");

	ServerWebExchange webExchange = testFilter(request, lbUrl);

	URI uri = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).hasScheme("http").hasHost("service1-host1").hasParameter("a", "b")
			.hasParameter("c", "d[]");

	// prove that it is NOT encoded
	assertThat(uri.getRawQuery()).isEqualTo("a=b&c=d[]");
}
 
Example 2
Source File: ResourceWebHandler.java    From java-technology-stack with 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 3
Source File: RouteToRequestUrlFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void encodedParameters() {
	URI url = UriComponentsBuilder.fromUriString("http://localhost/get?a=b&c=d[]")
			.buildAndExpand().encode().toUri();

	// prove that it is encoded
	assertThat(url.getRawQuery()).isEqualTo("a=b&c=d%5B%5D");

	assertThat(url).hasParameter("c", "d[]");

	MockServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, url)
			.build();

	ServerWebExchange webExchange = testFilter(request, "http://myhost");
	URI uri = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).hasScheme("http").hasHost("myhost").hasParameter("a", "b")
			.hasParameter("c", "d[]");

	// prove that it is not double encoded
	assertThat(uri.getRawQuery()).isEqualTo("a=b&c=d%5B%5D");
}
 
Example 4
Source File: RouteToRequestUrlFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void unencodedParameters() {
	URI url = URI.create("http://localhost/get?a=b&c=d[]");

	// prove that it is unencoded
	assertThat(url.getRawQuery()).isEqualTo("a=b&c=d[]");

	MockServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, url)
			.build();

	ServerWebExchange webExchange = testFilter(request, "http://myhost");

	URI uri = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).hasScheme("http").hasHost("myhost").hasParameter("a", "b")
			.hasParameter("c", "d[]");

	// prove that it is NOT encoded
	assertThat(uri.getRawQuery()).isEqualTo("a=b&c=d[]");
}
 
Example 5
Source File: WebsocketRoutingFilter.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	changeSchemeIfIsWebSocketUpgrade(exchange);

	URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	String scheme = requestUrl.getScheme();

	if (isAlreadyRouted(exchange)
			|| (!"ws".equals(scheme) && !"wss".equals(scheme))) {
		return chain.filter(exchange);
	}
	setAlreadyRouted(exchange);

	HttpHeaders headers = exchange.getRequest().getHeaders();
	HttpHeaders filtered = filterRequest(getHeadersFilters(), exchange);

	List<String> protocols = headers.get(SEC_WEBSOCKET_PROTOCOL);
	if (protocols != null) {
		protocols = headers.get(SEC_WEBSOCKET_PROTOCOL).stream().flatMap(
				header -> Arrays.stream(commaDelimitedListToStringArray(header)))
				.map(String::trim).collect(Collectors.toList());
	}

	return this.webSocketService.handleRequest(exchange, new ProxyWebSocketHandler(
			requestUrl, this.webSocketClient, filtered, protocols));
}
 
Example 6
Source File: WebsocketRoutingFilter.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
private void changeSchemeIfIsWebSocketUpgrade(ServerWebExchange exchange) {
	// Check the Upgrade
	URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	String scheme = requestUrl.getScheme().toLowerCase();
	String upgrade = exchange.getRequest().getHeaders().getUpgrade();
	// change the scheme if the socket client send a "http" or "https"
	if ("WebSocket".equalsIgnoreCase(upgrade)
			&& ("http".equals(scheme) || "https".equals(scheme))) {
		String wsScheme = convertHttpToWs(scheme);
		URI wsRequestUrl = UriComponentsBuilder.fromUri(requestUrl).scheme(wsScheme)
				.build().toUri();
		exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, wsRequestUrl);
		if (log.isTraceEnabled()) {
			log.trace("changeSchemeTo:[" + wsRequestUrl + "]");
		}
	}
}
 
Example 7
Source File: ForwardRoutingFilter.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);

	String scheme = requestUrl.getScheme();
	if (isAlreadyRouted(exchange) || !"forward".equals(scheme)) {
		return chain.filter(exchange);
	}

	// TODO: translate url?

	if (log.isTraceEnabled()) {
		log.trace("Forwarding to URI: " + requestUrl);
	}

	return this.getDispatcherHandler().handle(exchange);
}
 
Example 8
Source File: ReactiveLoadBalancerClientFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void encodedParameters() {
	URI url = UriComponentsBuilder.fromUriString("http://localhost/get?a=b&c=d[]")
			.buildAndExpand().encode().toUri();

	MockServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, url)
			.build();

	URI lbUrl = UriComponentsBuilder.fromUriString("lb://service1?a=b&c=d[]")
			.buildAndExpand().encode().toUri();

	// prove that it is encoded
	assertThat(lbUrl.getRawQuery()).isEqualTo("a=b&c=d%5B%5D");

	assertThat(lbUrl).hasParameter("c", "d[]");

	ServerWebExchange webExchange = testFilter(request, lbUrl);
	URI uri = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).hasScheme("http").hasHost("service1-host1").hasParameter("a", "b")
			.hasParameter("c", "d[]");

	// prove that it is not double encoded
	assertThat(uri.getRawQuery()).isEqualTo("a=b&c=d%5B%5D");
}
 
Example 9
Source File: PrefixPathGatewayFilterFactoryTest.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
private void testPrefixPathFilter(String prefix, String path, String expectedPath) {
	GatewayFilter filter = new PrefixPathGatewayFilterFactory()
			.apply(c -> c.setPrefix(prefix));
	MockServerHttpRequest request = MockServerHttpRequest
			.get("http://localhost" + path).build();

	ServerWebExchange exchange = MockServerWebExchange.from(request);

	GatewayFilterChain filterChain = mock(GatewayFilterChain.class);

	ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor
			.forClass(ServerWebExchange.class);
	when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());

	filter.filter(exchange, filterChain);

	ServerWebExchange webExchange = captor.getValue();

	assertThat(webExchange.getRequest().getURI()).hasPath(expectedPath);
	LinkedHashSet<URI> uris = webExchange
			.getRequiredAttribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
	assertThat(uris).contains(request.getURI());
}
 
Example 10
Source File: RouteToRequestUrlFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void encodedUrl() {
	URI url = UriComponentsBuilder.fromUriString("http://localhost/abc def/get")
			.buildAndExpand().encode().toUri();

	// prove that it is encoded
	assertThat(url.getRawPath()).isEqualTo("/abc%20def/get");

	assertThat(url).hasPath("/abc def/get");

	MockServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, url)
			.build();

	ServerWebExchange webExchange = testFilter(request,
			"http://myhost/abc%20def/get");
	URI uri = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).hasScheme("http").hasHost("myhost").hasPath("/abc def/get");

	// prove that it is not double encoded
	assertThat(uri.getRawPath()).isEqualTo("/abc%20def/get");
}
 
Example 11
Source File: RouteToRequestUrlFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void partialEncodedParameters() {
	assumeTrue("partialEncodedParameters ignored for boot 2.2",
			SpringBootVersion.getVersion().startsWith("2.3."));

	URI url = UriComponentsBuilder
			.fromUriString("http://localhost/get?key[]=test= key&start=1533108081")
			.build().toUri();

	// prove that it is partial encoded
	assertThat(url.getRawQuery()).isEqualTo("key[]=test=%20key&start=1533108081");

	assertThat(url).hasParameter("key[]", "test= key");
	assertThat(url).hasParameter("start", "1533108081");

	MockServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, url)
			.build();

	ServerWebExchange webExchange = testFilter(request, "http://myhost");
	URI uri = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).hasScheme("http").hasHost("myhost")
			// since https://github.com/joel-costigliola/assertj-core/issues/1699
			// assertj uses raw query
			.hasParameter("key[]", "test=%20key").hasParameter("start", "1533108081");

	// prove that it is double encoded since partial encoded uri is treated as
	// unencoded.
	assertThat(uri.getRawQuery()).isEqualTo("key[]=test=%2520key&start=1533108081");
}
 
Example 12
Source File: RouteToRequestUrlFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void happyPathLbPlusScheme() {
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost/getb")
			.build();

	ServerWebExchange webExchange = testFilter(request, "lb:http://myhost");
	URI uri = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).hasScheme("http").hasHost("myhost");
	String schemePrefix = webExchange
			.getRequiredAttribute(GATEWAY_SCHEME_PREFIX_ATTR);
	assertThat(schemePrefix).isEqualTo("lb");
}
 
Example 13
Source File: RouteToRequestUrlFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void happyPath() {
	MockServerHttpRequest request = MockServerHttpRequest
			.get("http://localhost/get?a=b").build();

	ServerWebExchange webExchange = testFilter(request, "http://myhost/mypath");
	URI uri = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).hasScheme("http").hasHost("myhost").hasPath("/get")
			.hasParameter("a", "b");
}
 
Example 14
Source File: ReactiveLoadBalancerClientFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void happyPath() {
	MockServerHttpRequest request = MockServerHttpRequest
			.get("http://localhost/get?a=b").build();

	URI lbUri = URI.create("lb://service1?a=b");
	ServerWebExchange webExchange = testFilter(request, lbUri);
	URI uri = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).hasScheme("http").hasHost("service1-host1").hasParameter("a",
			"b");
}
 
Example 15
Source File: RewritePathGatewayFilterFactoryTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
private ServerWebExchange testRewriteFilter(String regex, String replacement,
		String actualPath, String expectedPath) {
	GatewayFilter filter = new RewritePathGatewayFilterFactory()
			.apply(c -> c.setRegexp(regex).setReplacement(replacement));

	URI url = UriComponentsBuilder.fromUriString("http://localhost" + actualPath)
			.build(true).toUri();
	MockServerHttpRequest request = MockServerHttpRequest.method(HttpMethod.GET, url)
			.build();

	ServerWebExchange exchange = MockServerWebExchange.from(request);

	GatewayFilterChain filterChain = mock(GatewayFilterChain.class);

	ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor
			.forClass(ServerWebExchange.class);
	when(filterChain.filter(captor.capture())).thenReturn(Mono.empty());

	filter.filter(exchange, filterChain);

	ServerWebExchange webExchange = captor.getValue();

	assertThat(webExchange.getRequest().getURI()).hasPath(expectedPath);

	URI requestUrl = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(requestUrl).hasScheme("http").hasHost("localhost").hasNoPort()
			.hasPath(expectedPath);
	LinkedHashSet<URI> uris = webExchange
			.getRequiredAttribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
	assertThat(uris).contains(request.getURI());

	return webExchange;
}
 
Example 16
Source File: ServerWebExchangeUtils.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
public static void addOriginalRequestUrl(ServerWebExchange exchange, URI url) {
	exchange.getAttributes().computeIfAbsent(GATEWAY_ORIGINAL_REQUEST_URL_ATTR,
			s -> new LinkedHashSet<>());
	LinkedHashSet<URI> uris = exchange
			.getRequiredAttribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
	uris.add(url);
}
 
Example 17
Source File: ReactiveLoadBalancerClientFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void noQueryParams() {
	MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost/get")
			.build();

	ServerWebExchange webExchange = testFilter(request, URI.create("lb://service1"));
	URI uri = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
	assertThat(uri).hasScheme("http").hasHost("service1-host1");
}
 
Example 18
Source File: HandlerFunctionAdapter.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<HandlerResult> handle(ServerWebExchange exchange, Object handler) {
	HandlerFunction<?> handlerFunction = (HandlerFunction<?>) handler;
	ServerRequest request = exchange.getRequiredAttribute(RouterFunctions.REQUEST_ATTRIBUTE);
	return handlerFunction.handle(request)
			.map(response -> new HandlerResult(handlerFunction, response, HANDLER_FUNCTION_RETURN_TYPE));
}
 
Example 19
Source File: ForwardRoutingFilterTests.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldFilterAndKeepHostPathAsSpecified() {

	URI uri = UriComponentsBuilder.fromUriString("forward://host/outage").build()
			.toUri();
	exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, uri);

	ArgumentCaptor<ServerWebExchange> captor = ArgumentCaptor
			.forClass(ServerWebExchange.class);

	forwardRoutingFilter.filter(exchange, chain);

	verify(dispatcherHandler).handle(captor.capture());

	assertThat(exchange.getAttributes().get(GATEWAY_ALREADY_ROUTED_ATTR)).isNull();

	ServerWebExchange webExchange = captor.getValue();

	URI forwardedUrl = webExchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);

	assertThat(forwardedUrl).hasScheme("forward").hasHost("host").hasPath("/outage");
}
 
Example 20
Source File: WebClientHttpRoutingFilter.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);

	String scheme = requestUrl.getScheme();
	if (isAlreadyRouted(exchange)
			|| (!"http".equals(scheme) && !"https".equals(scheme))) {
		return chain.filter(exchange);
	}
	setAlreadyRouted(exchange);

	ServerHttpRequest request = exchange.getRequest();

	HttpMethod method = request.getMethod();

	HttpHeaders filteredHeaders = filterRequest(getHeadersFilters(), exchange);

	boolean preserveHost = exchange
			.getAttributeOrDefault(PRESERVE_HOST_HEADER_ATTRIBUTE, false);

	RequestBodySpec bodySpec = this.webClient.method(method).uri(requestUrl)
			.headers(httpHeaders -> {
				httpHeaders.addAll(filteredHeaders);
				// TODO: can this support preserviceHostHeader?
				if (!preserveHost) {
					httpHeaders.remove(HttpHeaders.HOST);
				}
			});

	RequestHeadersSpec<?> headersSpec;
	if (requiresBody(method)) {
		headersSpec = bodySpec.body(BodyInserters.fromDataBuffers(request.getBody()));
	}
	else {
		headersSpec = bodySpec;
	}

	return headersSpec.exchange()
			// .log("webClient route")
			.flatMap(res -> {
				ServerHttpResponse response = exchange.getResponse();
				response.getHeaders().putAll(res.headers().asHttpHeaders());
				response.setStatusCode(res.statusCode());
				// Defer committing the response until all route filters have run
				// Put client response as ServerWebExchange attribute and write
				// response later NettyWriteResponseFilter
				exchange.getAttributes().put(CLIENT_RESPONSE_ATTR, res);
				return chain.filter(exchange);
			});
}