org.springframework.cloud.gateway.route.Route Java Examples

The following examples show how to use org.springframework.cloud.gateway.route.Route. 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: BaseWebClientTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Bean
@Order(500)
public GlobalFilter modifyResponseFilter() {
	return (exchange, chain) -> {
		log.info("modifyResponseFilter start");
		String value = exchange.getAttributeOrDefault(GATEWAY_HANDLER_MAPPER_ATTR,
				"N/A");
		if (!exchange.getResponse().isCommitted()) {
			exchange.getResponse().getHeaders().add(HANDLER_MAPPER_HEADER, value);
		}
		Route route = exchange.getAttributeOrDefault(GATEWAY_ROUTE_ATTR, null);
		if (route != null) {
			if (!exchange.getResponse().isCommitted()) {
				exchange.getResponse().getHeaders().add(ROUTE_ID_HEADER,
						route.getId());
			}
		}
		return chain.filter(exchange);
	};
}
 
Example #2
Source File: ExRetryGatewayFilterFactory.java    From wecube-platform with Apache License 2.0 6 votes vote down vote up
private void tryPrepareRoute(ServerWebExchange exchange) {
    DynamicRouteContext routeContext = exchange.getAttribute(DynamicRouteContext.DYNAMIC_ROUTE_CONTEXT_KEY);
    if (routeContext == null) {
        log.debug("routeContext is null for {}", exchange.getRequest().getURI().toString());
        return;
    }

    HttpDestination httpDest = routeContext.next();
    if (httpDest == null) {
        log.debug("dynamic route item info is null for {}", exchange.getRequest().getURI().toString());
        return;
    }

    if (log.isDebugEnabled()) {
        log.debug("prepare dynamic route:{},last round:{}", httpDest,
                exchange.getAttribute(EX_RETRY_ITERATION_KEY));
    }

    Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
    String baseUrl = String.format("%s://%s:%s", httpDest.getScheme(), httpDest.getHost(), httpDest.getPort());
    URI newUri = UriComponentsBuilder.fromHttpUrl(baseUrl).build().toUri();
    ServerWebExchangeUtils.addOriginalRequestUrl(exchange, exchange.getRequest().getURI());
    Route newRoute = Route.async().asyncPredicate(route.getPredicate()).filters(route.getFilters())
            .id(route.getId()).order(route.getOrder()).uri(newUri).build();
    exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR, newRoute);
}
 
Example #3
Source File: RouteProvider.java    From syncope with Apache License 2.0 6 votes vote down vote up
public List<Route.AsyncBuilder> fetch() {
    synchronized (this) {
        if (client == null) {
            try {
                client = new SyncopeClientFactoryBean().
                        setAddress(serviceOps.get(NetworkService.Type.CORE).getAddress()).
                        setUseCompression(useGZIPCompression).
                        create(new AnonymousAuthenticationHandler(anonymousUser, anonymousKey));
            } catch (Exception e) {
                LOG.error("Could not init SyncopeClient", e);
                return List.of();
            }
        }
    }

    synchronized (routeTOs) {
        routeTOs.clear();
        routeTOs.addAll(client.getService(SRARouteService.class).list());
    }

    return routeTOs.stream().map(this::toRoute).collect(Collectors.toList());
}
 
Example #4
Source File: RoutePredicateHandlerMappingTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void lookupRouteFromSyncPredicates() {
	Route routeFalse = Route.async().id("routeFalse").uri("http://localhost")
			.predicate(swe -> false).build();
	Route routeFail = Route.async().id("routeFail").uri("http://localhost")
			.predicate(swe -> {
				throw new IllegalStateException("boom");
			}).build();
	Route routeTrue = Route.async().id("routeTrue").uri("http://localhost")
			.predicate(swe -> true).build();
	RouteLocator routeLocator = () -> Flux.just(routeFalse, routeFail, routeTrue)
			.hide();
	RoutePredicateHandlerMapping mapping = new RoutePredicateHandlerMapping(null,
			routeLocator, new GlobalCorsProperties(), new MockEnvironment());

	final Mono<Route> routeMono = mapping
			.lookupRoute(Mockito.mock(ServerWebExchange.class));

	StepVerifier.create(routeMono.map(Route::getId)).expectNext("routeTrue")
			.verifyComplete();

	outputCapture
			.expect(containsString("Error applying predicate for route: routeFail"));
	outputCapture.expect(containsString("java.lang.IllegalStateException: boom"));
}
 
Example #5
Source File: DiscoveryClientRouteDefinitionLocatorIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void newServiceAddsRoute() throws Exception {
	List<Route> routes = routeLocator.getRoutes()
			.filter(route -> route.getId().startsWith("test__")).collectList()
			.block();
	assertThat(routes).hasSize(1);

	discoveryClient.multiple();

	publisher.publishEvent(new HeartbeatEvent(this, 1L));

	Thread.sleep(2000);

	routes = routeLocator.getRoutes()
			.filter(route -> route.getId().startsWith("test__")).collectList()
			.block();
	assertThat(routes).hasSize(2);
}
 
Example #6
Source File: RedisRateLimiterConfigTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
private void assertFilter(String key, int replenishRate, int burstCapacity,
		int requestedTokens, boolean useDefaultConfig) {
	RedisRateLimiter.Config config;

	if (useDefaultConfig) {
		config = rateLimiter.getDefaultConfig();
	}
	else {
		assertThat(rateLimiter.getConfig()).containsKey(key);
		config = rateLimiter.getConfig().get(key);
	}
	assertThat(config).isNotNull();
	assertThat(config.getReplenishRate()).isEqualTo(replenishRate);
	assertThat(config.getBurstCapacity()).isEqualTo(burstCapacity);
	assertThat(config.getRequestedTokens()).isEqualTo(requestedTokens);

	Route route = routeLocator.getRoutes().filter(r -> r.getId().equals(key)).next()
			.block();
	assertThat(route).isNotNull();
	assertThat(route.getFilters()).hasSize(1);
}
 
Example #7
Source File: GatewayControllerEndpoint.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
Map<String, Object> serialize(Route route) {
	HashMap<String, Object> r = new HashMap<>();
	r.put("route_id", route.getId());
	r.put("uri", route.getUri().toString());
	r.put("order", route.getOrder());
	r.put("predicate", route.getPredicate().toString());
	if (!CollectionUtils.isEmpty(route.getMetadata())) {
		r.put("metadata", route.getMetadata());
	}

	ArrayList<String> filters = new ArrayList<>();

	for (int i = 0; i < route.getFilters().size(); i++) {
		GatewayFilter gatewayFilter = route.getFilters().get(i);
		filters.add(gatewayFilter.toString());
	}

	r.put("filters", filters);
	return r;
}
 
Example #8
Source File: GatewayFilterSpecTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSetModifyBodyResponseFilterWithConfigConsumer() {
	ConfigurableApplicationContext context = mock(
			ConfigurableApplicationContext.class);
	Route.AsyncBuilder routeBuilder = Route.async().id("123").uri("abc:123")
			.predicate(exchange -> true);

	when(context.getBean(ModifyResponseBodyGatewayFilterFactory.class))
			.thenReturn(new ModifyResponseBodyGatewayFilterFactory(
					HandlerStrategies.withDefaults().messageReaders(),
					Collections.emptySet(), Collections.emptySet()));

	RouteLocatorBuilder.Builder routes = new RouteLocatorBuilder(context).routes();
	GatewayFilterSpec spec = new GatewayFilterSpec(routeBuilder, routes);
	spec.modifyResponseBody(
			(smth) -> new ModifyResponseBodyGatewayFilterFactory.Config()
					.setRewriteFunction(String.class, String.class,
							(exchange, s) -> Mono.just(s)));

	Route route = routeBuilder.build();
	assertThat(route.getFilters()).hasSize(1);

	assertFilter(route.getFilters().get(0),
			ModifyResponseBodyGatewayFilterFactory.ModifyResponseGatewayFilter.class,
			NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 1);
}
 
Example #9
Source File: GatewayFilterSpecTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void testFilters() {
	ConfigurableApplicationContext context = mock(
			ConfigurableApplicationContext.class);
	Route.AsyncBuilder routeBuilder = Route.async().id("123").uri("abc:123")
			.predicate(exchange -> true);
	RouteLocatorBuilder.Builder routes = new RouteLocatorBuilder(context).routes();
	GatewayFilterSpec spec = new GatewayFilterSpec(routeBuilder, routes);
	spec.filters(new MyUnorderedFilter(), new MyOrderedFilter());

	Route route = routeBuilder.build();
	assertThat(route.getFilters()).hasSize(2);

	assertFilter(route.getFilters().get(0), OrderedGatewayFilter.class, 0);
	assertFilter(route.getFilters().get(1), MyOrderedFilter.class, 1000);
}
 
Example #10
Source File: GatewayFilterSpecTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSetModifyBodyResponseFilterWithRewriteFunction() {
	ConfigurableApplicationContext context = mock(
			ConfigurableApplicationContext.class);
	Route.AsyncBuilder routeBuilder = Route.async().id("123").uri("abc:123")
			.predicate(exchange -> true);

	when(context.getBean(ModifyResponseBodyGatewayFilterFactory.class))
			.thenReturn(new ModifyResponseBodyGatewayFilterFactory(
					HandlerStrategies.withDefaults().messageReaders(),
					Collections.emptySet(), Collections.emptySet()));

	RouteLocatorBuilder.Builder routes = new RouteLocatorBuilder(context).routes();
	GatewayFilterSpec spec = new GatewayFilterSpec(routeBuilder, routes);
	spec.modifyResponseBody(String.class, String.class,
			(exchange, s) -> Mono.just(s));

	Route route = routeBuilder.build();
	assertThat(route.getFilters()).hasSize(1);

	assertFilter(route.getFilters().get(0),
			ModifyResponseBodyGatewayFilterFactory.ModifyResponseGatewayFilter.class,
			NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 1);
}
 
Example #11
Source File: FilteringWebHandler.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@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);

	if (logger.isDebugEnabled()) {
		logger.debug("Sorted gatewayFilterFactories: " + combined);
	}

	return new DefaultGatewayFilterChain(combined).filter(exchange);
}
 
Example #12
Source File: GatewayFilterSpecTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSetModifyBodyResponseFilterWithRewriteFunctionAndEmptyBodySupplier() {
	ConfigurableApplicationContext context = mock(
			ConfigurableApplicationContext.class);
	Route.AsyncBuilder routeBuilder = Route.async().id("123").uri("abc:123")
			.predicate(exchange -> true);

	when(context.getBean(ModifyResponseBodyGatewayFilterFactory.class))
			.thenReturn(new ModifyResponseBodyGatewayFilterFactory(
					HandlerStrategies.withDefaults().messageReaders(),
					Collections.emptySet(), Collections.emptySet()));

	RouteLocatorBuilder.Builder routes = new RouteLocatorBuilder(context).routes();
	GatewayFilterSpec spec = new GatewayFilterSpec(routeBuilder, routes);
	spec.modifyResponseBody(String.class, String.class,
			(exchange, s) -> Mono.just(s == null ? "emptybody" : s));

	Route route = routeBuilder.build();
	assertThat(route.getFilters()).hasSize(1);

	assertFilter(route.getFilters().get(0),
			ModifyResponseBodyGatewayFilterFactory.ModifyResponseGatewayFilter.class,
			NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 1);
}
 
Example #13
Source File: RouteEnhanceServiceImpl.java    From FEBS-Cloud with Apache License 2.0 6 votes vote down vote up
@Override
public void saveRequestLogs(ServerWebExchange exchange) {
    URI originUri = getGatewayOriginalRequestUrl(exchange);
    // /auth/user为令牌校验请求,是系统自发行为,非用户请求,故不记录
    if (!StringUtils.equalsIgnoreCase(TOKEN_CHECK_URL, originUri.getPath())) {
        URI url = getGatewayRequestUrl(exchange);
        Route route = getGatewayRoute(exchange);
        ServerHttpRequest request = exchange.getRequest();
        String ipAddress = FebsUtil.getServerHttpRequestIpAddress(request);
        if (url != null && route != null) {
            RouteLog routeLog = RouteLog.builder()
                    .ip(ipAddress)
                    .requestUri(originUri.getPath())
                    .targetServer(route.getId())
                    .targetUri(url.getPath())
                    .requestMethod(request.getMethodValue())
                    .location(AddressUtil.getCityInfo(ipAddress))
                    .build();
            routeLogService.create(routeLog).subscribe();
        }
    }
}
 
Example #14
Source File: GatewayFilterSpecTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSetModifyBodyResponseFilterWithRewriteFunctionAndNewContentType() {
	ConfigurableApplicationContext context = mock(
			ConfigurableApplicationContext.class);
	Route.AsyncBuilder routeBuilder = Route.async().id("123").uri("abc:123")
			.predicate(exchange -> true);

	when(context.getBean(ModifyResponseBodyGatewayFilterFactory.class))
			.thenReturn(new ModifyResponseBodyGatewayFilterFactory(
					HandlerStrategies.withDefaults().messageReaders(),
					Collections.emptySet(), Collections.emptySet()));

	RouteLocatorBuilder.Builder routes = new RouteLocatorBuilder(context).routes();
	GatewayFilterSpec spec = new GatewayFilterSpec(routeBuilder, routes);
	spec.modifyResponseBody(String.class, String.class,
			MediaType.APPLICATION_JSON_VALUE, (exchange, s) -> Mono.just(s));

	Route route = routeBuilder.build();
	assertThat(route.getFilters()).hasSize(1);

	assertFilter(route.getFilters().get(0),
			ModifyResponseBodyGatewayFilterFactory.ModifyResponseGatewayFilter.class,
			NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 1);
}
 
Example #15
Source File: GatewayFilterSpecTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
private void testFilter(Class<? extends GatewayFilter> type,
		GatewayFilter gatewayFilter, int order) {
	ConfigurableApplicationContext context = mock(
			ConfigurableApplicationContext.class);
	Route.AsyncBuilder routeBuilder = Route.async().id("123").uri("abc:123")
			.predicate(exchange -> true);
	RouteLocatorBuilder.Builder routes = new RouteLocatorBuilder(context).routes();
	GatewayFilterSpec spec = new GatewayFilterSpec(routeBuilder, routes);
	spec.filter(gatewayFilter);

	Route route = routeBuilder.build();
	assertThat(route.getFilters()).hasSize(1);
	assertFilter(route.getFilters().get(0), type, order);
}
 
Example #16
Source File: ForwardPathFilter.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
	URI routeUri = route.getUri();
	String scheme = routeUri.getScheme();
	if (isAlreadyRouted(exchange) || !"forward".equals(scheme)) {
		return chain.filter(exchange);
	}
	exchange = exchange.mutate()
			.request(exchange.getRequest().mutate().path(routeUri.getPath()).build())
			.build();
	return chain.filter(exchange);
}
 
Example #17
Source File: CsrfRouteMatcher.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean routeBehavior(final Route route) {
    return routeProvider.getRouteTOs().stream().
            filter(r -> route.getId().equals(r.getKey())).findFirst().
            map(SRARouteTO::isCsrf).orElse(true)
            && !publicRouteMatcher.routeBehavior(route);
}
 
Example #18
Source File: RoutePredicateHandlerMappingTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void lookupRouteFromAsyncPredicates() {
	Route routeFalse = Route.async().id("routeFalse").uri("http://localhost")
			.asyncPredicate(swe -> Mono.just(false)).build();
	Route routeError = Route.async().id("routeError").uri("http://localhost")
			.asyncPredicate(swe -> Mono.error(new IllegalStateException("boom1")))
			.build();
	Route routeFail = Route.async().id("routeFail").uri("http://localhost")
			.asyncPredicate(swe -> {
				throw new IllegalStateException("boom2");
			}).build();
	Route routeTrue = Route.async().id("routeTrue").uri("http://localhost")
			.asyncPredicate(swe -> Mono.just(true)).build();
	RouteLocator routeLocator = () -> Flux
			.just(routeFalse, routeError, routeFail, routeTrue).hide();
	RoutePredicateHandlerMapping mapping = new RoutePredicateHandlerMapping(null,
			routeLocator, new GlobalCorsProperties(), new MockEnvironment());

	final Mono<Route> routeMono = mapping
			.lookupRoute(Mockito.mock(ServerWebExchange.class));

	StepVerifier.create(routeMono.map(Route::getId)).expectNext("routeTrue")
			.verifyComplete();

	outputCapture
			.expect(containsString("Error applying predicate for route: routeError"));
	outputCapture.expect(containsString("java.lang.IllegalStateException: boom1"));

	outputCapture
			.expect(containsString("Error applying predicate for route: routeFail"));
	outputCapture.expect(containsString("java.lang.IllegalStateException: boom2"));
}
 
Example #19
Source File: RedisRateLimiterDefaultFilterConfigTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
private void assertConfigAndRoute(String key, int replenishRate, int burstCapacity,
		int requestedTokens, RedisRateLimiter.Config config) {
	assertThat(config).isNotNull();
	assertThat(config.getReplenishRate()).isEqualTo(replenishRate);
	assertThat(config.getBurstCapacity()).isEqualTo(burstCapacity);
	assertThat(config.getRequestedTokens()).isEqualTo(requestedTokens);

	Route route = routeLocator.getRoutes().filter(r -> r.getId().equals(key)).next()
			.block();
	assertThat(route).isNotNull();
	assertThat(route.getFilters()).isNotEmpty();
}
 
Example #20
Source File: RouteToRequestUrlFilter.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
	if (route == null) {
		return chain.filter(exchange);
	}
	log.trace("RouteToRequestUrlFilter start");
	URI uri = exchange.getRequest().getURI();
	boolean encoded = containsEncodedParts(uri);
	URI routeUri = route.getUri();

	if (hasAnotherScheme(routeUri)) {
		// this is a special url, save scheme to special attribute
		// replace routeUri with schemeSpecificPart
		exchange.getAttributes().put(GATEWAY_SCHEME_PREFIX_ATTR,
				routeUri.getScheme());
		routeUri = URI.create(routeUri.getSchemeSpecificPart());
	}

	if ("lb".equalsIgnoreCase(routeUri.getScheme()) && routeUri.getHost() == null) {
		// Load balanced URIs should always have a host. If the host is null it is
		// most
		// likely because the host name was invalid (for example included an
		// underscore)
		throw new IllegalStateException("Invalid host: " + routeUri.toString());
	}

	URI mergedUrl = UriComponentsBuilder.fromUri(uri)
			// .uri(routeUri)
			.scheme(routeUri.getScheme()).host(routeUri.getHost())
			.port(routeUri.getPort()).build(encoded).toUri();
	exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, mergedUrl);
	return chain.filter(exchange);
}
 
Example #21
Source File: AdaptCachedBodyGlobalFilter.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	// the cached ServerHttpRequest is used when the ServerWebExchange can not be
	// mutated, for example, during a predicate where the body is read, but still
	// needs to be cached.
	ServerHttpRequest cachedRequest = exchange
			.getAttributeOrDefault(CACHED_SERVER_HTTP_REQUEST_DECORATOR_ATTR, null);
	if (cachedRequest != null) {
		exchange.getAttributes().remove(CACHED_SERVER_HTTP_REQUEST_DECORATOR_ATTR);
		return chain.filter(exchange.mutate().request(cachedRequest).build());
	}

	//
	DataBuffer body = exchange.getAttributeOrDefault(CACHED_REQUEST_BODY_ATTR, null);
	Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);

	if (body != null || !this.routesToCache.containsKey(route.getId())) {
		return chain.filter(exchange);
	}

	return ServerWebExchangeUtils.cacheRequestBody(exchange, (serverHttpRequest) -> {
		// don't mutate and build if same request object
		if (serverHttpRequest == exchange.getRequest()) {
			return chain.filter(exchange);
		}
		return chain.filter(exchange.mutate().request(serverHttpRequest).build());
	});
}
 
Example #22
Source File: NettyRoutingFilter.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
private Duration getResponseTimeout(Route route) {
	Object responseTimeoutAttr = route.getMetadata().get(RESPONSE_TIMEOUT_ATTR);
	Long responseTimeout = null;
	if (responseTimeoutAttr != null) {
		if (responseTimeoutAttr instanceof Number) {
			responseTimeout = ((Number) responseTimeoutAttr).longValue();
		}
		else {
			responseTimeout = Long.valueOf(responseTimeoutAttr.toString());
		}
	}
	return responseTimeout != null ? Duration.ofMillis(responseTimeout)
			: properties.getResponseTimeout();
}
 
Example #23
Source File: NettyRoutingFilter.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new HttpClient with per route timeout configuration. Sub-classes that
 * override, should call super.getHttpClient() if they want to honor the per route
 * timeout configuration.
 * @param route the current route.
 * @param exchange the current ServerWebExchange.
 * @param chain the current GatewayFilterChain.
 * @return
 */
protected HttpClient getHttpClient(Route route, ServerWebExchange exchange) {
	Object connectTimeoutAttr = route.getMetadata().get(CONNECT_TIMEOUT_ATTR);
	if (connectTimeoutAttr != null) {
		Integer connectTimeout = getInteger(connectTimeoutAttr);
		return this.httpClient.tcpConfiguration((tcpClient) -> tcpClient
				.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout));
	}
	return httpClient;
}
 
Example #24
Source File: GatewayRouteTagsProvider.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public Tags apply(ServerWebExchange exchange) {
	Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);

	if (route != null) {
		return Tags.of("routeId", route.getId(), "routeUri",
				route.getUri().toString());
	}

	return Tags.empty();
}
 
Example #25
Source File: RoutePredicateHandlerMapping.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
protected Mono<Route> lookupRoute(ServerWebExchange exchange) {
	return this.routeLocator.getRoutes()
			// individually filter routes so that filterWhen error delaying is not a
			// problem
			.concatMap(route -> Mono.just(route).filterWhen(r -> {
				// add the current route we are testing
				exchange.getAttributes().put(GATEWAY_PREDICATE_ROUTE_ATTR, r.getId());
				return r.getPredicate().apply(exchange);
			})
					// instead of immediately stopping main flux due to error, log and
					// swallow it
					.doOnError(e -> logger.error(
							"Error applying predicate for route: " + route.getId(),
							e))
					.onErrorResume(e -> Mono.empty()))
			// .defaultIfEmpty() put a static Route not found
			// or .switchIfEmpty()
			// .switchIfEmpty(Mono.<Route>empty().log("noroute"))
			.next()
			// TODO: error handling
			.map(route -> {
				if (logger.isDebugEnabled()) {
					logger.debug("Route matched: " + route.getId());
				}
				validateRoute(route, exchange);
				return route;
			});

	/*
	 * TODO: trace logging if (logger.isTraceEnabled()) {
	 * logger.trace("RouteDefinition did not match: " + routeDefinition.getId()); }
	 */
}
 
Example #26
Source File: RoutePredicateHandlerMapping.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
protected Mono<?> getHandlerInternal(ServerWebExchange exchange) {
	// don't handle requests on management port if set and different than server port
	if (this.managementPortType == DIFFERENT && this.managementPort != null
			&& exchange.getRequest().getURI().getPort() == this.managementPort) {
		return Mono.empty();
	}
	exchange.getAttributes().put(GATEWAY_HANDLER_MAPPER_ATTR, getSimpleName());

	return lookupRoute(exchange)
			// .log("route-predicate-handler-mapping", Level.FINER) //name this
			.flatMap((Function<Route, Mono<?>>) r -> {
				exchange.getAttributes().remove(GATEWAY_PREDICATE_ROUTE_ATTR);
				if (logger.isDebugEnabled()) {
					logger.debug(
							"Mapping [" + getExchangeDesc(exchange) + "] to " + r);
				}

				exchange.getAttributes().put(GATEWAY_ROUTE_ATTR, r);
				return Mono.just(webHandler);
			}).switchIfEmpty(Mono.empty().then(Mono.fromRunnable(() -> {
				exchange.getAttributes().remove(GATEWAY_PREDICATE_ROUTE_ATTR);
				if (logger.isTraceEnabled()) {
					logger.trace("No RouteDefinition found for ["
							+ getExchangeDesc(exchange) + "]");
				}
			})));
}
 
Example #27
Source File: TraceRequestHttpHeadersFilter.java    From java-spring-cloud with Apache License 2.0 5 votes vote down vote up
private String getRouteId(ServerWebExchange exchange) {
  String routeId = "unknown";
  Route route = exchange.getAttribute(ROUTE_ATTRIBUTE);
  if (Objects.nonNull(route)) {
    return route.getId();
  }
  return routeId;
}
 
Example #28
Source File: DynamicRouteGatewayFilterFactory.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
protected void tryPrepareDynamicRoute(ServerWebExchange exchange, Route originalRoute) {
    String path = exchange.getRequest().getURI().getPath();
    String componentPath = calculateComponentPath(path);
    HttpMethod httpMethod = exchange.getRequest().getMethod();
    MvcHttpMethodAndPathConfig methodAndPathConfig = DynamicRouteItemInfoHolder.findRouteConfig(componentPath, path,
            httpMethod);

    List<HttpDestination> httpDestinations = null;
    if (methodAndPathConfig == null) {
        httpDestinations = DynamicRouteItemInfoHolder.findDefaultRouteConfig(componentPath, path, httpMethod);
    } else {
        httpDestinations = methodAndPathConfig.getHttpDestinations();
    }

    if (httpDestinations.isEmpty()) {
        log.debug("cannot find http destination for {}", path);
        return;
    }

    DynamicRouteContext routeContext = DynamicRouteContext.newInstance().addHttpDestinations(httpDestinations)
            .sortByWeight();

    exchange.getAttributes().put(DynamicRouteContext.DYNAMIC_ROUTE_CONTEXT_KEY, routeContext);

    if (routeContext.hasNext()) {
        HttpDestination httpDest = routeContext.next();
        String baseUrl = String.format("%s://%s:%s", httpDest.getScheme(), httpDest.getHost(), httpDest.getPort());
        trySetGatewayRouteAttribute(exchange, originalRoute, baseUrl);
    }

    return;
}
 
Example #29
Source File: DynamicRouteGatewayFilterFactory.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
protected void trySetGatewayRouteAttribute(ServerWebExchange exchange, Route route, String baseUrl) {
    if (log.isDebugEnabled()) {
        log.debug("base url:{}", baseUrl);
    }

    URI newUri = UriComponentsBuilder.fromHttpUrl(baseUrl).build().toUri();
    ServerWebExchangeUtils.addOriginalRequestUrl(exchange, exchange.getRequest().getURI());

    Route newRoute = Route.async().asyncPredicate(route.getPredicate()).filters(route.getFilters())
            .id(route.getId()).order(route.getOrder()).uri(newUri).build();

    exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR, newRoute);
}
 
Example #30
Source File: DynamicRouteGatewayFilterFactory.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
@Override
public GatewayFilter apply(Config config) {
    if (log.isDebugEnabled()) {
        log.debug("Filter-{} applied", DynamicRouteGatewayFilterFactory.class.getSimpleName());
    }
    return ((exchange, chain) -> {
        log.debug("Filter-IN-{}, uri:{}", DynamicRouteGatewayFilterFactory.class.getSimpleName(),
                exchange.getRequest().getURI().toString());

        boolean enabled = config.isEnabled();

        if (!enabled) {
            return chain.filter(exchange);
        }

        Route originalRoute = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);

        if (originalRoute == null) {
            log.debug("There is none route found for filter:{}",
                    DynamicRouteGatewayFilterFactory.class.getSimpleName());
            return chain.filter(exchange);
        }

        tryPrepareDynamicRoute(exchange, originalRoute);

        try {
            return chain.filter(exchange);
        } catch (Exception e) {
            log.debug("errors while exchanging", e);
            return Mono.justOrEmpty(null);
        }
    });
}