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

The following examples show how to use org.springframework.web.server.ServerWebExchange#getAttributeOrDefault() . 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: PathVariableMapMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Object resolveArgumentValue(
		MethodParameter methodParameter, BindingContext context, ServerWebExchange exchange) {

	String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
	return exchange.getAttributeOrDefault(name, Collections.emptyMap());
}
 
Example 2
Source File: MockServerSpecTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
	String name = "test-attribute";
	String value = exchange.getAttributeOrDefault(name, "");
	exchange.getAttributes().put(name, value + ":" + this.name);
	return chain.filter(exchange);
}
 
Example 3
Source File: PathVariableMapMethodArgumentResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Object resolveArgumentValue(
		MethodParameter methodParameter, BindingContext context, ServerWebExchange exchange) {

	String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
	return exchange.getAttributeOrDefault(name, Collections.emptyMap());
}
 
Example 4
Source File: MockServerSpecTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
	String name = "test-attribute";
	String value = exchange.getAttributeOrDefault(name, "");
	exchange.getAttributes().put(name, value + ":" + this.name);
	return chain.filter(exchange);
}
 
Example 5
Source File: WeightRoutePredicateFactory.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public Predicate<ServerWebExchange> apply(WeightConfig config) {
	return new GatewayPredicate() {
		@Override
		public boolean test(ServerWebExchange exchange) {
			Map<String, String> weights = exchange.getAttributeOrDefault(WEIGHT_ATTR,
					Collections.emptyMap());

			String routeId = exchange.getAttribute(GATEWAY_PREDICATE_ROUTE_ATTR);

			// all calculations and comparison against random num happened in
			// WeightCalculatorWebFilter
			String group = config.getGroup();
			if (weights.containsKey(group)) {

				String chosenRoute = weights.get(group);
				if (log.isTraceEnabled()) {
					log.trace("in group weight: " + group + ", current route: "
							+ routeId + ", chosen route: " + chosenRoute);
				}

				return routeId.equals(chosenRoute);
			}
			else if (log.isTraceEnabled()) {
				log.trace("no weights found for group: " + group + ", current route: "
						+ routeId);
			}

			return false;
		}

		@Override
		public String toString() {
			return String.format("Weight: %s %s", config.getGroup(),
					config.getWeight());
		}
	};
}
 
Example 6
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 7
Source File: RetryGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
public void reset(ServerWebExchange exchange) {
	// TODO: what else to do to reset exchange?
	Set<String> addedHeaders = exchange.getAttributeOrDefault(
			CLIENT_RESPONSE_HEADER_NAMES, Collections.emptySet());
	addedHeaders
			.forEach(header -> exchange.getResponse().getHeaders().remove(header));
	removeAlreadyRouted(exchange);
}
 
Example 8
Source File: PrefixPathGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public GatewayFilter apply(Config config) {
	return new GatewayFilter() {
		@Override
		public Mono<Void> filter(ServerWebExchange exchange,
				GatewayFilterChain chain) {
			boolean alreadyPrefixed = exchange
					.getAttributeOrDefault(GATEWAY_ALREADY_PREFIXED_ATTR, false);
			if (alreadyPrefixed) {
				return chain.filter(exchange);
			}
			exchange.getAttributes().put(GATEWAY_ALREADY_PREFIXED_ATTR, true);

			ServerHttpRequest req = exchange.getRequest();
			addOriginalRequestUrl(exchange, req.getURI());
			String newPath = config.prefix + req.getURI().getRawPath();

			ServerHttpRequest request = req.mutate().path(newPath).build();

			exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, request.getURI());

			if (log.isTraceEnabled()) {
				log.trace("Prefixed URI with: " + config.prefix + " -> "
						+ request.getURI());
			}

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

		@Override
		public String toString() {
			return filterToStringCreator(PrefixPathGatewayFilterFactory.this)
					.append("prefix", config.getPrefix()).toString();
		}
	};
}
 
Example 9
Source File: RedirectView.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private Map<String, String> getCurrentUriVariables(ServerWebExchange exchange) {
	String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
	return exchange.getAttributeOrDefault(name, Collections.<String, String>emptyMap());
}
 
Example 10
Source File: ExRetryGatewayFilterFactory.java    From wecube-platform with Apache License 2.0 4 votes vote down vote up
public void reset(ServerWebExchange exchange) {
    Set<String> addedHeaders = exchange.getAttributeOrDefault(CLIENT_RESPONSE_HEADER_NAMES, Collections.emptySet());
    addedHeaders.forEach(header -> exchange.getResponse().getHeaders().remove(header));
    exchange.getAttributes().remove(GATEWAY_ALREADY_ROUTED_ATTR);
}
 
Example 11
Source File: RedirectView.java    From java-technology-stack with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private Map<String, String> getCurrentUriVariables(ServerWebExchange exchange) {
	String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
	return exchange.getAttributeOrDefault(name, Collections.<String, String>emptyMap());
}
 
Example 12
Source File: ServerWebExchangeUtils.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
public static boolean isAlreadyRouted(ServerWebExchange exchange) {
	return exchange.getAttributeOrDefault(GATEWAY_ALREADY_ROUTED_ATTR, false);
}
 
Example 13
Source File: ServerWebExchangeUtils.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
public static Map<String, String> getUriTemplateVariables(
		ServerWebExchange exchange) {
	return exchange.getAttributeOrDefault(URI_TEMPLATE_VARIABLES_ATTRIBUTE,
			new HashMap<>());
}
 
Example 14
Source File: RetryGatewayFilterFactory.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
private void updateIteration(ServerWebExchange exchange) {
	int iteration = exchange.getAttributeOrDefault(RETRY_ITERATION_KEY, -1);
	int newIteration = iteration + 1;
	trace("setting new iteration in attr %d", () -> newIteration);
	exchange.getAttributes().put(RETRY_ITERATION_KEY, newIteration);
}
 
Example 15
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);
			});
}