Search in sources :

Example 1 with GatewayFilter

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;
}
Also used : ServerWebExchange(org.springframework.web.server.ServerWebExchange) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) MockServerHttpRequest(org.springframework.mock.http.server.reactive.MockServerHttpRequest) GatewayFilterChain(org.springframework.cloud.gateway.filter.GatewayFilterChain) URI(java.net.URI) GatewayFilter(org.springframework.cloud.gateway.filter.GatewayFilter)

Example 2 with GatewayFilter

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());
}
Also used : ServerWebExchange(org.springframework.web.server.ServerWebExchange) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) PathMatchInfo(org.springframework.web.util.pattern.PathPattern.PathMatchInfo) MockServerHttpRequest(org.springframework.mock.http.server.reactive.MockServerHttpRequest) GatewayFilterChain(org.springframework.cloud.gateway.filter.GatewayFilterChain) URI(java.net.URI) GatewayFilter(org.springframework.cloud.gateway.filter.GatewayFilter)

Example 3 with GatewayFilter

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);
}
Also used : ArrayList(java.util.ArrayList) Route(org.springframework.cloud.gateway.route.Route) OrderedGatewayFilter(org.springframework.cloud.gateway.filter.OrderedGatewayFilter) GatewayFilter(org.springframework.cloud.gateway.filter.GatewayFilter)

Example 4 with GatewayFilter

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();
        }));
    };
}
Also used : HttpStatus(org.springframework.http.HttpStatus) ServerWebExchangeUtils(org.springframework.cloud.gateway.support.ServerWebExchangeUtils) RateLimiter(org.springframework.cloud.gateway.filter.ratelimit.RateLimiter) GatewayFilter(org.springframework.cloud.gateway.filter.GatewayFilter) KeyResolver(org.springframework.cloud.gateway.filter.ratelimit.KeyResolver) Route(org.springframework.cloud.gateway.route.Route) KeyResolver(org.springframework.cloud.gateway.filter.ratelimit.KeyResolver) Route(org.springframework.cloud.gateway.route.Route)

Example 5 with GatewayFilter

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;
}
Also used : ShortcutConfigurable(org.springframework.cloud.gateway.support.ShortcutConfigurable) Validator(org.springframework.validation.Validator) TupleBuilder(org.springframework.tuple.TupleBuilder) RoutePredicateFactory(org.springframework.cloud.gateway.handler.predicate.RoutePredicateFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) OrderedGatewayFilter(org.springframework.cloud.gateway.filter.OrderedGatewayFilter) FilterArgsEvent(org.springframework.cloud.gateway.event.FilterArgsEvent) PredicateArgsEvent(org.springframework.cloud.gateway.event.PredicateArgsEvent) ArrayList(java.util.ArrayList) ServerWebExchange(org.springframework.web.server.ServerWebExchange) LinkedHashMap(java.util.LinkedHashMap) BeanFactoryAware(org.springframework.beans.factory.BeanFactoryAware) Map(java.util.Map) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) ApplicationEventPublisherAware(org.springframework.context.ApplicationEventPublisherAware) GatewayProperties(org.springframework.cloud.gateway.config.GatewayProperties) GatewayFilterFactory(org.springframework.cloud.gateway.filter.factory.GatewayFilterFactory) ShortcutConfigurable.getValue(org.springframework.cloud.gateway.support.ShortcutConfigurable.getValue) Predicate(java.util.function.Predicate) FilterDefinition(org.springframework.cloud.gateway.filter.FilterDefinition) BeansException(org.springframework.beans.BeansException) Collectors(java.util.stream.Collectors) PredicateDefinition(org.springframework.cloud.gateway.handler.predicate.PredicateDefinition) Flux(reactor.core.publisher.Flux) List(java.util.List) ConfigurationUtils(org.springframework.cloud.gateway.support.ConfigurationUtils) Tuple(org.springframework.tuple.Tuple) BeanFactory(org.springframework.beans.factory.BeanFactory) ShortcutConfigurable.normalizeKey(org.springframework.cloud.gateway.support.ShortcutConfigurable.normalizeKey) GatewayFilter(org.springframework.cloud.gateway.filter.GatewayFilter) Log(org.apache.commons.logging.Log) SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) LogFactory(org.apache.commons.logging.LogFactory) AnnotationAwareOrderComparator(org.springframework.core.annotation.AnnotationAwareOrderComparator) ArrayList(java.util.ArrayList) FilterArgsEvent(org.springframework.cloud.gateway.event.FilterArgsEvent) OrderedGatewayFilter(org.springframework.cloud.gateway.filter.OrderedGatewayFilter) GatewayFilterFactory(org.springframework.cloud.gateway.filter.factory.GatewayFilterFactory) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) OrderedGatewayFilter(org.springframework.cloud.gateway.filter.OrderedGatewayFilter) GatewayFilter(org.springframework.cloud.gateway.filter.GatewayFilter) Tuple(org.springframework.tuple.Tuple)

Aggregations

GatewayFilter (org.springframework.cloud.gateway.filter.GatewayFilter)9 GatewayFilterChain (org.springframework.cloud.gateway.filter.GatewayFilterChain)5 ServerWebExchange (org.springframework.web.server.ServerWebExchange)5 URI (java.net.URI)4 Route (org.springframework.cloud.gateway.route.Route)4 MockServerHttpRequest (org.springframework.mock.http.server.reactive.MockServerHttpRequest)4 MockServerWebExchange (org.springframework.mock.web.server.MockServerWebExchange)4 OrderedGatewayFilter (org.springframework.cloud.gateway.filter.OrderedGatewayFilter)3 HttpStatus (org.springframework.http.HttpStatus)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Autowired (org.springframework.beans.factory.annotation.Autowired)2 Tuple (org.springframework.tuple.Tuple)2 Mono (reactor.core.publisher.Mono)2 HystrixCommandGroupKey (com.netflix.hystrix.HystrixCommandGroupKey)1 HystrixCommandKey (com.netflix.hystrix.HystrixCommandKey)1 HystrixObservableCommand (com.netflix.hystrix.HystrixObservableCommand)1 Setter (com.netflix.hystrix.HystrixObservableCommand.Setter)1 HystrixRuntimeException (com.netflix.hystrix.exception.HystrixRuntimeException)1 TIMEOUT (com.netflix.hystrix.exception.HystrixRuntimeException.FailureType.TIMEOUT)1