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

The following examples show how to use org.springframework.web.server.ServerWebExchange#getAttribute() . 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: AuthFilter.java    From gateway with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 生成返回数据
 *
 * @param exchange ServerWebExchange
 * @return Mono
 */
private Mono<Void> initResponse(ServerWebExchange exchange) {
    //设置headers
    ServerHttpResponse response = exchange.getResponse();
    HttpHeaders httpHeaders = response.getHeaders();
    httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
    httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");

    //设置body
    String json = Json.toJson(reply);
    logger.warn("返回数据: {}", json);
    DataBuffer body = response.bufferFactory().wrap(json.getBytes());

    Long startTime = exchange.getAttribute(COUNT_START_TIME);
    if (startTime != null) {
        long duration = (System.currentTimeMillis() - startTime);
        logger.info("处理时间: {} ms", duration);
    }

    return response.writeWith(Mono.just(body));
}
 
Example 2
Source File: BodyParamPlugin.java    From soul with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> execute(final ServerWebExchange exchange, final SoulPluginChain chain) {
    final ServerHttpRequest request = exchange.getRequest();
    final SoulContext soulContext = exchange.getAttribute(Constants.CONTEXT);
    if (Objects.nonNull(soulContext) && RpcTypeEnum.DUBBO.getName().equals(soulContext.getRpcType())) {
        MediaType mediaType = request.getHeaders().getContentType();
        ServerRequest serverRequest = ServerRequest.create(exchange, messageReaders);
        return serverRequest.bodyToMono(String.class)
                .switchIfEmpty(Mono.defer(() -> Mono.just("")))
                .flatMap(body -> {
                    if (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType)) {
                        exchange.getAttributes().put(Constants.DUBBO_PARAMS, body);
                    }
                    return chain.execute(exchange);
                });
    }
    return chain.execute(exchange);
}
 
Example 3
Source File: WrapperResponseFilter.java    From gateway with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 响应消息输出过滤器
 *
 * @param exchange ServerWebExchange
 * @param chain    GatewayFilterChain
 * @return Mono
 */
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpResponse originalResponse = exchange.getResponse();
    ServerHttpResponseDecorator responseDecorator = new ServerHttpResponseDecorator(originalResponse) {

        @Override
        public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
            Boolean logResult = exchange.getAttribute("logResult");
            if (logResult == null || !logResult) {
                return super.writeWith(body);
            }

            if (body instanceof Flux) {
                Flux<? extends DataBuffer> fluxBody = Flux.from(body);

                return super.writeWith(fluxBody.buffer().map(dataBuffers -> {
                    List<String> list = new ArrayList<>();
                    dataBuffers.forEach(dataBuffer -> {
                        byte[] content = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(content);
                        DataBufferUtils.release(dataBuffer);
                        list.add(new String(content, StandardCharsets.UTF_8));
                    });

                    String json = String.join("", list);
                    logger.info("返回数据: {}", json);

                    return bufferFactory().wrap(json.getBytes());
                }));
            }

            return super.writeWith(body);
        }
    };
    // replace response with decorator
    return chain.filter(exchange.mutate().response(responseDecorator).build());
}
 
Example 4
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 5
Source File: MatrixVariableMapMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Nullable
@Override
public Object resolveArgumentValue(MethodParameter parameter, BindingContext bindingContext,
		ServerWebExchange exchange) {

	Map<String, MultiValueMap<String, String>> matrixVariables =
			exchange.getAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE);

	if (CollectionUtils.isEmpty(matrixVariables)) {
		return Collections.emptyMap();
	}

	MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
	MatrixVariable annotation = parameter.getParameterAnnotation(MatrixVariable.class);
	Assert.state(annotation != null, "No MatrixVariable annotation");
	String pathVariable = annotation.pathVar();

	if (!pathVariable.equals(ValueConstants.DEFAULT_NONE)) {
		MultiValueMap<String, String> mapForPathVariable = matrixVariables.get(pathVariable);
		if (mapForPathVariable == null) {
			return Collections.emptyMap();
		}
		map.putAll(mapForPathVariable);
	}
	else {
		for (MultiValueMap<String, String> vars : matrixVariables.values()) {
			vars.forEach((name, values) -> {
				for (String value : values) {
					map.add(name, value);
				}
			});
		}
	}

	return (isSingleValueMap(parameter) ? map.toSingleValueMap() : map);
}
 
Example 6
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 7
Source File: WingtipsSpringWebfluxWebFilter.java    From wingtips with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method for null-safe extraction of a request attribute as a String.
 *
 * @param exchange The {@link ServerWebExchange} to inspect for request attributes.
 * @param attrName The desired request attribute name.
 * @return The desired request attribute value as a string, or null if no such request attribute could be found.
 */
protected static @Nullable String getRequestAttributeAsString(
    @NotNull ServerWebExchange exchange,
    @NotNull String attrName
) {
    Object attrValue = exchange.getAttribute(attrName);
    return (attrValue == null) ? null : attrValue.toString();
}
 
Example 8
Source File: MatrixVariableMapMethodArgumentResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Nullable
@Override
public Object resolveArgumentValue(MethodParameter parameter, BindingContext bindingContext,
		ServerWebExchange exchange) {

	Map<String, MultiValueMap<String, String>> matrixVariables =
			exchange.getAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE);

	if (CollectionUtils.isEmpty(matrixVariables)) {
		return Collections.emptyMap();
	}

	MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
	MatrixVariable annotation = parameter.getParameterAnnotation(MatrixVariable.class);
	Assert.state(annotation != null, "No MatrixVariable annotation");
	String pathVariable = annotation.pathVar();

	if (!pathVariable.equals(ValueConstants.DEFAULT_NONE)) {
		MultiValueMap<String, String> mapForPathVariable = matrixVariables.get(pathVariable);
		if (mapForPathVariable == null) {
			return Collections.emptyMap();
		}
		map.putAll(mapForPathVariable);
	}
	else {
		for (MultiValueMap<String, String> vars : matrixVariables.values()) {
			vars.forEach((name, values) -> {
				for (String value : values) {
					map.add(name, value);
				}
			});
		}
	}

	return (isSingleValueMap(parameter) ? map.toSingleValueMap() : map);
}
 
Example 9
Source File: TraceWebFilter.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
MonoWebFilterTrace(Mono<? extends Void> source, ServerWebExchange exchange,
		boolean initialTracePresent, TraceWebFilter parent) {
	super(source);
	this.tracer = parent.tracer();
	this.handler = parent.handler();
	this.exchange = exchange;
	this.attrSpan = exchange.getAttribute(TRACE_REQUEST_ATTR);
	this.initialTracePresent = initialTracePresent;
}
 
Example 10
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 11
Source File: PreSignatureFilter.java    From open-cloud with MIT License 5 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    String requestPath = request.getURI().getPath();
    if (apiProperties.getCheckSign() && !notSign(requestPath)) {
        try {
            Map params = Maps.newHashMap();
            GatewayContext gatewayContext = exchange.getAttribute(GatewayContext.CACHE_GATEWAY_CONTEXT);
            // 排除文件上传
            if (gatewayContext != null) {
                params = gatewayContext.getAllRequestData().toSingleValueMap();
            }
            // 验证请求参数
            SignatureUtils.validateParams(params);
            //开始验证签名
            if (baseAppServiceClient != null) {
                String appId = params.get(CommonConstants.SIGN_APP_ID_KEY).toString();
                // 获取客户端信息
                ResultBody<BaseApp> result = baseAppServiceClient.getApp(appId);
                BaseApp app = result.getData();
                if (app == null || app.getAppId() == null) {
                    return signatureDeniedHandler.handle(exchange, new OpenSignatureException("appId无效"));
                }
                // 服务器验证签名结果
                if (!SignatureUtils.validateSign(params, app.getSecretKey())) {
                    return signatureDeniedHandler.handle(exchange, new OpenSignatureException("签名验证失败!"));
                }
            }
        } catch (Exception ex) {
            return signatureDeniedHandler.handle(exchange, new OpenSignatureException(ex.getMessage()));
        }
    }
    return chain.filter(exchange);
}
 
Example 12
Source File: AbstractMatchStrategy.java    From soul with Apache License 2.0 5 votes vote down vote up
/**
 * Build real data string.
 *
 * @param condition the condition
 * @param exchange  the exchange
 * @return the string
 */
String buildRealData(final ConditionData condition, final ServerWebExchange exchange) {
    String realData = "";
    ParamTypeEnum paramTypeEnum = ParamTypeEnum.getParamTypeEnumByName(condition.getParamType());
    switch (paramTypeEnum) {
        case HEADER:
            final HttpHeaders headers = exchange.getRequest().getHeaders();
            final List<String> list = headers.get(condition.getParamName());
            if (CollectionUtils.isEmpty(list)) {
                return realData;
            }
            realData = Objects.requireNonNull(headers.get(condition.getParamName())).stream().findFirst().orElse("");
            break;
        case URI:
            realData = exchange.getRequest().getURI().getPath();
            break;
        case QUERY:
            final MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
            realData = queryParams.getFirst(condition.getParamName());
            break;
        case HOST:
            realData = HostAddressUtils.acquireHost(exchange);
            break;
        case IP:
            realData = HostAddressUtils.acquireIp(exchange);
            break;
        case POST:
            final SoulContext soulContext = exchange.getAttribute(Constants.CONTEXT);
            realData = (String) ReflectUtils.getFieldValue(soulContext, condition.getParamName());
            break;
        default:
            break;
    }
    return realData;
}
 
Example 13
Source File: MatrixVariableMethodArgumentResolver.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Nullable
@Override
protected Object resolveNamedValue(String name, MethodParameter param, ServerWebExchange exchange) {
	Map<String, MultiValueMap<String, String>> pathParameters =
			exchange.getAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE);
	if (CollectionUtils.isEmpty(pathParameters)) {
		return null;
	}

	MatrixVariable ann = param.getParameterAnnotation(MatrixVariable.class);
	Assert.state(ann != null, "No MatrixVariable annotation");
	String pathVar = ann.pathVar();
	List<String> paramValues = null;

	if (!pathVar.equals(ValueConstants.DEFAULT_NONE)) {
		if (pathParameters.containsKey(pathVar)) {
			paramValues = pathParameters.get(pathVar).get(name);
		}
	}
	else {
		boolean found = false;
		paramValues = new ArrayList<>();
		for (MultiValueMap<String, String> params : pathParameters.values()) {
			if (params.containsKey(name)) {
				if (found) {
					String paramType = param.getNestedParameterType().getName();
					throw new ServerErrorException(
							"Found more than one match for URI path parameter '" + name +
							"' for parameter type [" + paramType + "]. Use 'pathVar' attribute to disambiguate.",
							param, null);
				}
				paramValues.addAll(params.get(name));
				found = true;
			}
		}
	}

	if (CollectionUtils.isEmpty(paramValues)) {
		return null;
	}
	else if (paramValues.size() == 1) {
		return paramValues.get(0);
	}
	else {
		return paramValues;
	}
}
 
Example 14
Source File: ReadBodyPredicateFactory.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
@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 15
Source File: DividePlugin.java    From soul with Apache License 2.0 4 votes vote down vote up
@Override
public Boolean skip(final ServerWebExchange exchange) {
    final SoulContext soulContext = exchange.getAttribute(Constants.CONTEXT);
    return !Objects.equals(Objects.requireNonNull(soulContext).getRpcType(), RpcTypeEnum.HTTP.getName());
}
 
Example 16
Source File: RouteEnhanceServiceImpl.java    From FEBS-Cloud with Apache License 2.0 4 votes vote down vote up
private Route getGatewayRoute(ServerWebExchange exchange) {
    return exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
}
 
Example 17
Source File: RouteEnhanceServiceImpl.java    From FEBS-Cloud with Apache License 2.0 4 votes vote down vote up
private URI getGatewayRequestUrl(ServerWebExchange exchange) {
    return exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
}
 
Example 18
Source File: TraceWebFilter.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
private boolean spanWithoutParent(ServerWebExchange exchange) {
	return exchange.getAttribute(TRACE_SPAN_WITHOUT_PARENT) != null;
}
 
Example 19
Source File: HandlerResultHandlerSupport.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private List<MediaType> getProducibleTypes(
		ServerWebExchange exchange, Supplier<List<MediaType>> producibleTypesSupplier) {

	Set<MediaType> mediaTypes = exchange.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
	return (mediaTypes != null ? new ArrayList<>(mediaTypes) : producibleTypesSupplier.get());
}
 
Example 20
Source File: SpringCloudPlugin.java    From soul with Apache License 2.0 2 votes vote down vote up
/**
 * plugin is execute.
 *
 * @param exchange the current server exchange
 * @return default false.
 */
@Override
public Boolean skip(final ServerWebExchange exchange) {
    final SoulContext body = exchange.getAttribute(Constants.CONTEXT);
    return !Objects.equals(Objects.requireNonNull(body).getRpcType(), RpcTypeEnum.SPRING_CLOUD.getName());
}