use of org.springframework.cloud.gateway.filter.GatewayFilter in project spring-cloud-gateway by spring-cloud.
the class RewritePathGatewayFilterFactoryTests method testRewriteFilter.
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;
}
use of org.springframework.cloud.gateway.filter.GatewayFilter in project spring-cloud-gateway by spring-cloud.
the class SetPathGatewayFilterFactoryTests method testFilter.
private void testFilter(String template, String expectedPath, HashMap<String, String> variables) {
GatewayFilter filter = new SetPathGatewayFilterFactory().apply(c -> c.setTemplate(template));
MockServerHttpRequest request = MockServerHttpRequest.get("http://localhost").build();
ServerWebExchange exchange = MockServerWebExchange.from(request);
try {
Constructor<PathMatchInfo> constructor = ReflectionUtils.accessibleConstructor(PathMatchInfo.class, Map.class, Map.class);
constructor.setAccessible(true);
PathMatchInfo pathMatchInfo = constructor.newInstance(variables, Collections.emptyMap());
exchange.getAttributes().put(URI_TEMPLATE_VARIABLES_ATTRIBUTE, pathMatchInfo);
} catch (Exception e) {
ReflectionUtils.rethrowRuntimeException(e);
}
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());
}
use of org.springframework.cloud.gateway.filter.GatewayFilter in project spring-cloud-gateway by spring-cloud.
the class FilteringWebHandler method handle.
/* TODO: relocate @EventListener(RefreshRoutesEvent.class)
void handleRefresh() {
this.combinedFiltersForRoute.clear();
}*/
@Override
public Mono<Void> handle(ServerWebExchange exchange) {
Route route = exchange.getRequiredAttribute(GATEWAY_ROUTE_ATTR);
List<GatewayFilter> gatewayFilters = route.getFilters();
List<GatewayFilter> combined = new ArrayList<>(this.globalFilters);
combined.addAll(gatewayFilters);
// TODO: needed or cached?
AnnotationAwareOrderComparator.sort(combined);
logger.debug("Sorted gatewayFilterFactories: " + combined);
return new DefaultGatewayFilterChain(combined).filter(exchange);
}
use of org.springframework.cloud.gateway.filter.GatewayFilter in project spring-cloud-gateway by spring-cloud.
the class RequestRateLimiterGatewayFilterFactory method apply.
@SuppressWarnings("unchecked")
@Override
public GatewayFilter apply(Config config) {
KeyResolver resolver = (config.keyResolver == null) ? defaultKeyResolver : config.keyResolver;
RateLimiter<Object> limiter = (config.rateLimiter == null) ? defaultRateLimiter : config.rateLimiter;
return (exchange, chain) -> {
Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
return resolver.resolve(exchange).flatMap(key -> limiter.isAllowed(route.getId(), key).flatMap(response -> {
if (response.isAllowed()) {
return chain.filter(exchange);
}
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
return exchange.getResponse().setComplete();
}));
};
}
use of org.springframework.cloud.gateway.filter.GatewayFilter in project spring-cloud-gateway by spring-cloud.
the class RouteDefinitionRouteLocator method loadGatewayFilters.
@SuppressWarnings("unchecked")
private List<GatewayFilter> loadGatewayFilters(String id, List<FilterDefinition> filterDefinitions) {
List<GatewayFilter> filters = filterDefinitions.stream().map(definition -> {
GatewayFilterFactory factory = this.gatewayFilterFactories.get(definition.getName());
if (factory == null) {
throw new IllegalArgumentException("Unable to find GatewayFilterFactory with name " + definition.getName());
}
Map<String, String> args = definition.getArgs();
if (logger.isDebugEnabled()) {
logger.debug("RouteDefinition " + id + " applying filter " + args + " to " + definition.getName());
}
if (factory.isConfigurable()) {
Map<String, Object> properties = factory.shortcutType().normalize(args, factory, this.parser, this.beanFactory);
Object configuration = factory.newConfig();
ConfigurationUtils.bind(configuration, properties, factory.shortcutFieldPrefix(), definition.getName(), validator);
GatewayFilter gatewayFilter = factory.apply(configuration);
if (this.publisher != null) {
this.publisher.publishEvent(new FilterArgsEvent(this, id, properties));
}
return gatewayFilter;
} else {
Tuple tuple = getTuple(factory, args, this.parser, this.beanFactory);
return factory.apply(tuple);
}
}).collect(Collectors.toList());
ArrayList<GatewayFilter> ordered = new ArrayList<>(filters.size());
for (int i = 0; i < filters.size(); i++) {
ordered.add(new OrderedGatewayFilter(filters.get(i), i + 1));
}
return ordered;
}
Aggregations