Java Code Examples for org.springframework.cloud.gateway.support.ServerWebExchangeUtils

The following examples show how to use org.springframework.cloud.gateway.support.ServerWebExchangeUtils. 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
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 2
Source Project: alcor   Source File: KeystoneAuthWebFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    String token = exchange.getRequest().getHeaders().getFirst(AUTHORIZE_TOKEN);
    if(token == null){
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }
    String projectId = keystoneClient.verifyToken(token);
    if("".equals(projectId)){
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }
    // rewrite uri path include project id
    ServerHttpRequest req = exchange.getRequest();
    ServerWebExchangeUtils.addOriginalRequestUrl(exchange, req.getURI());
    String path = req.getURI().getRawPath();
    String newPath = path.replaceAll(neutronUrlPrefix, "/project/" + projectId);
    ServerHttpRequest request = req.mutate().path(newPath).build();
    exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, request.getURI());
    return chain.filter(exchange.mutate().request(request).build());
}
 
Example 3
@Override
public Predicate<ServerWebExchange> apply(Config config) {
	return new GatewayPredicate() {
		@Override
		public boolean test(ServerWebExchange exchange) {
			String host = exchange.getRequest().getHeaders().getFirst("Host");
			Optional<String> optionalPattern = config.getPatterns().stream()
					.filter(pattern -> pathMatcher.match(pattern, host)).findFirst();

			if (optionalPattern.isPresent()) {
				Map<String, String> variables = pathMatcher
						.extractUriTemplateVariables(optionalPattern.get(), host);
				ServerWebExchangeUtils.putUriTemplateVariables(exchange, variables);
				return true;
			}

			return false;
		}

		@Override
		public String toString() {
			return String.format("Hosts: %s", config.getPatterns());
		}
	};
}
 
Example 4
@Override
public GatewayFilter apply(NameValueConfig config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			String value = ServerWebExchangeUtils.expand(exchange, config.getValue());
			exchange.getResponse().getHeaders().add(config.getName(), value);

			return chain.filter(exchange);
		}

		@Override
		public String toString() {
			return filterToStringCreator(AddResponseHeaderGatewayFilterFactory.this)
					.append(config.getName(), config.getValue()).toString();
		}
	};
}
 
Example 5
@Override
public GatewayFilter apply(NameValueConfig config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			String value = ServerWebExchangeUtils.expand(exchange, config.getValue());
			ServerHttpRequest request = exchange.getRequest().mutate()
					.headers(httpHeaders -> httpHeaders.set(config.name, value))
					.build();

			return chain.filter(exchange.mutate().request(request).build());
		}

		@Override
		public String toString() {
			return filterToStringCreator(SetRequestHeaderGatewayFilterFactory.this)
					.append(config.getName(), config.getValue()).toString();
		}
	};
}
 
Example 6
@Override
public GatewayFilter apply(NameValueConfig config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			String value = ServerWebExchangeUtils.expand(exchange, config.getValue());
			ServerHttpRequest request = exchange.getRequest().mutate()
					.header(config.getName(), value).build();

			return chain.filter(exchange.mutate().request(request).build());
		}

		@Override
		public String toString() {
			return filterToStringCreator(AddRequestHeaderGatewayFilterFactory.this)
					.append(config.getName(), config.getValue()).toString();
		}
	};
}
 
Example 7
@Override
public GatewayFilter apply(NameValueConfig config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			String value = ServerWebExchangeUtils.expand(exchange, config.getValue());
			return chain.filter(exchange).then(Mono.fromRunnable(() -> exchange
					.getResponse().getHeaders().set(config.name, value)));
		}

		@Override
		public String toString() {
			return filterToStringCreator(SetResponseHeaderGatewayFilterFactory.this)
					.append(config.getName(), config.getValue()).toString();
		}
	};
}
 
Example 8
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);
	ServerWebExchangeUtils.putUriTemplateVariables(exchange, variables);

	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 9
Source Project: syncope   Source File: SyncopeSRAWebExceptionHandler.java    License: Apache License 2.0 6 votes vote down vote up
private URI getError(final ServerWebExchange exchange) {
    URI error = globalError;
    String routeId = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_PREDICATE_ROUTE_ATTR);
    if (StringUtils.isNotBlank(routeId)) {
        Optional<URI> routeError = Optional.ofNullable(CACHE.get(routeId)).orElseGet(() -> {
            URI uri = null;
            Optional<SRARouteTO> route = routeProvider.getRouteTOs().stream().
                    filter(r -> routeId.equals(r.getKey())).findFirst();
            if (route.isPresent()) {
                uri = route.get().getError();
            }

            return CACHE.put(routeId, Optional.ofNullable(uri));
        });
        if (routeError.isPresent()) {
            error = routeError.get();
        }
    }

    return error;
}
 
Example 10
@Override
public AsyncPredicate<ServerWebExchange> applyAsync(final Config config) {
    return exchange -> {
        JsonNode cachedBody = exchange.getAttribute(CACHE_REQUEST_BODY_OBJECT_KEY);
        if (cachedBody == null) {
            return ServerWebExchangeUtils.cacheRequestBodyAndRequest(
                    exchange, serverHttpRequest -> ServerRequest.create(
                            exchange.mutate().request(serverHttpRequest).build(), MESSAGE_READERS).
                            bodyToMono(JsonNode.class).
                            doOnNext(objectValue -> exchange.getAttributes().
                            put(CACHE_REQUEST_BODY_OBJECT_KEY, objectValue)).
                            map(objectValue -> objectValue.has(config.getData())));
        } else {
            return Mono.just(cachedBody.has(config.getData()));
        }
    };
}
 
Example 11
Source Project: FEBS-Cloud   Source File: RouteEnhanceServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
private URI getGatewayOriginalRequestUrl(ServerWebExchange exchange) {
    LinkedHashSet<URI> uris = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
    URI originUri = null;
    if (uris != null) {
        originUri = uris.stream().findFirst().orElse(null);
    }
    return originUri;
}
 
Example 12
@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);
        }
    });
}
 
Example 13
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 14
@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 15
@Override
public GatewayFilter apply(Config config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			String value = ServerWebExchangeUtils.expand(exchange, config.getHost());

			ServerHttpRequest request = exchange.getRequest().mutate()
					.headers(httpHeaders -> {
						httpHeaders.remove("Host");
						httpHeaders.add("Host", value);
					}).build();

			// Make sure the header we just set is preserved
			exchange.getAttributes().put(PRESERVE_HOST_HEADER_ATTRIBUTE, true);

			return chain.filter(exchange.mutate().request(request).build());
		}

		@Override
		public String toString() {
			return filterToStringCreator(
					SetRequestHostHeaderGatewayFilterFactory.this)
							.append(config.getHost()).toString();
		}
	};
}
 
Example 16
Source Project: syncope   Source File: AbstractRouteMatcher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Mono<MatchResult> matches(final ServerWebExchange exchange) {
    // see org.springframework.cloud.gateway.handler.RoutePredicateHandlerMapping#lookupRoute
    return routeLocator.getRoutes().
            // individually filter routes so that filterWhen error delaying is not a problem
            concatMap(route -> Mono.just(route).filterWhen(r -> r.getPredicate().apply(exchange)).
            // instead of immediately stopping main flux due to error, log and swallow it
            doOnError(e -> LOG.error("Error applying predicate for route: {}", route.getId(), e)).
            onErrorResume(e -> Mono.empty())).
            next().
            flatMap(route -> {
                exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_PREDICATE_ROUTE_ATTR, route.getId());
                LOG.debug("[{}] Route found: {}", getClass().getName(), route);

                boolean cond = Optional.ofNullable(CACHE.get(getCacheName()).get(route.getId())).orElseGet(() -> {
                    boolean result = routeBehavior(route);
                    CACHE.get(getCacheName()).put(route.getId(), result);
                    return result;
                });
                LOG.debug("[{}] Condition matched: {}", getClass().getName(), cond);

                return cond ? MatchResult.match() : MatchResult.notMatch();
            }).switchIfEmpty(Mono.defer(() -> {
        LOG.debug("[{}] No Route found", getClass().getName());
        return MatchResult.notMatch();
    }));
}
 
Example 17
private URI endpointUri(
        final WebFilterExchange exchange,
        final URI endSessionEndpoint,
        final Authentication authentication) {

    UriComponentsBuilder builder = UriComponentsBuilder.fromUri(endSessionEndpoint);
    builder.queryParam("id_token_hint", idToken(authentication));

    URI postLogout = globalPostLogout;
    String routeId = exchange.getExchange().getAttribute(ServerWebExchangeUtils.GATEWAY_PREDICATE_ROUTE_ATTR);
    if (StringUtils.isNotBlank(routeId)) {
        Optional<URI> routePostLogout = Optional.ofNullable(CACHE.get(routeId)).orElseGet(() -> {
            URI uri = null;
            Optional<SRARouteTO> route = routeProvider.getRouteTOs().stream().
                    filter(r -> routeId.equals(r.getKey())).findFirst();
            if (route.isPresent()) {
                uri = route.get().getPostLogout();
            }

            return CACHE.put(routeId, Optional.ofNullable(uri));
        });
        if (routePostLogout.isPresent()) {
            postLogout = routePostLogout.get();
        }
    }
    builder.queryParam("post_logout_redirect_uri", postLogout);

    return builder.encode(StandardCharsets.UTF_8).build().toUri();
}
 
Example 18
Source Project: FEBS-Cloud   Source File: RouteEnhanceServiceImpl.java    License: Apache License 2.0 4 votes vote down vote up
private URI getGatewayRequestUrl(ServerWebExchange exchange) {
    return exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
}
 
Example 19
Source Project: FEBS-Cloud   Source File: RouteEnhanceServiceImpl.java    License: Apache License 2.0 4 votes vote down vote up
private Route getGatewayRoute(ServerWebExchange exchange) {
    return exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
}
 
Example 20
@Override
@SuppressWarnings("unchecked")
public AsyncPredicate<ServerWebExchange> applyAsync(Config config) {
	return new AsyncPredicate<ServerWebExchange>() {
		@Override
		public Publisher<Boolean> apply(ServerWebExchange exchange) {
			Class inClass = config.getInClass();

			Object cachedBody = exchange.getAttribute(CACHE_REQUEST_BODY_OBJECT_KEY);
			Mono<?> modifiedBody;
			// We can only read the body from the request once, once that happens if
			// we try to read the body again an exception will be thrown. The below
			// if/else caches the body object as a request attribute in the
			// ServerWebExchange so if this filter is run more than once (due to more
			// than one route using it) we do not try to read the request body
			// multiple times
			if (cachedBody != null) {
				try {
					boolean test = config.predicate.test(cachedBody);
					exchange.getAttributes().put(TEST_ATTRIBUTE, test);
					return Mono.just(test);
				}
				catch (ClassCastException e) {
					if (log.isDebugEnabled()) {
						log.debug("Predicate test failed because class in predicate "
								+ "does not match the cached body object", e);
					}
				}
				return Mono.just(false);
			}
			else {
				return ServerWebExchangeUtils.cacheRequestBodyAndRequest(exchange,
						(serverHttpRequest) -> ServerRequest
								.create(exchange.mutate().request(serverHttpRequest)
										.build(), messageReaders)
								.bodyToMono(inClass)
								.doOnNext(objectValue -> exchange.getAttributes().put(
										CACHE_REQUEST_BODY_OBJECT_KEY, objectValue))
								.map(objectValue -> config.getPredicate()
										.test(objectValue)));
			}
		}

		@Override
		public String toString() {
			return String.format("ReadBody: %s", config.getInClass());
		}
	};
}
 
Example 21
@SuppressWarnings("unchecked")
@Override
public GatewayFilter apply(Config config) {
	KeyResolver resolver = getOrDefault(config.keyResolver, defaultKeyResolver);
	RateLimiter<Object> limiter = getOrDefault(config.rateLimiter,
			defaultRateLimiter);
	boolean denyEmpty = getOrDefault(config.denyEmptyKey, this.denyEmptyKey);
	HttpStatusHolder emptyKeyStatus = HttpStatusHolder
			.parse(getOrDefault(config.emptyKeyStatus, this.emptyKeyStatusCode));

	return (exchange, chain) -> resolver.resolve(exchange).defaultIfEmpty(EMPTY_KEY)
			.flatMap(key -> {
				if (EMPTY_KEY.equals(key)) {
					if (denyEmpty) {
						setResponseStatus(exchange, emptyKeyStatus);
						return exchange.getResponse().setComplete();
					}
					return chain.filter(exchange);
				}
				String routeId = config.getRouteId();
				if (routeId == null) {
					Route route = exchange
							.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
					routeId = route.getId();
				}
				return limiter.isAllowed(routeId, key).flatMap(response -> {

					for (Map.Entry<String, String> header : response.getHeaders()
							.entrySet()) {
						exchange.getResponse().getHeaders().add(header.getKey(),
								header.getValue());
					}

					if (response.isAllowed()) {
						return chain.filter(exchange);
					}

					setResponseStatus(exchange, config.getStatusCode());
					return exchange.getResponse().setComplete();
				});
			});
}
 
Example 22
@Override
public GatewayFilter apply(NameValueConfig config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			URI uri = exchange.getRequest().getURI();
			StringBuilder query = new StringBuilder();
			String originalQuery = uri.getRawQuery();

			if (StringUtils.hasText(originalQuery)) {
				query.append(originalQuery);
				if (originalQuery.charAt(originalQuery.length() - 1) != '&') {
					query.append('&');
				}
			}

			String value = ServerWebExchangeUtils.expand(exchange, config.getValue());
			// TODO urlencode?
			query.append(config.getName());
			query.append('=');
			query.append(value);

			try {
				URI newUri = UriComponentsBuilder.fromUri(uri)
						.replaceQuery(query.toString()).build(true).toUri();

				ServerHttpRequest request = exchange.getRequest().mutate().uri(newUri)
						.build();

				return chain.filter(exchange.mutate().request(request).build());
			}
			catch (RuntimeException ex) {
				throw new IllegalStateException(
						"Invalid URI query: \"" + query.toString() + "\"");
			}
		}

		@Override
		public String toString() {
			return filterToStringCreator(AddRequestParameterGatewayFilterFactory.this)
					.append(config.getName(), config.getValue()).toString();
		}
	};
}
 
Example 23
Source Project: spring-cloud-gateway   Source File: Route.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public AsyncPredicate<ServerWebExchange> getPredicate() {
	return ServerWebExchangeUtils.toAsyncPredicate(this.predicate);
}