Example usage for org.springframework.web.server ServerWebExchange getAttributes

List of usage examples for org.springframework.web.server ServerWebExchange getAttributes

Introduction

In this page you can find the example usage for org.springframework.web.server ServerWebExchange getAttributes.

Prototype

Map<String, Object> getAttributes();

Source Link

Document

Return a mutable map of request attributes for the current exchange.

Usage

From source file:org.springframework.boot.actuate.autoconfigure.cloudfoundry.reactive.CloudFoundrySecurityInterceptor.java

private Mono<Void> check(ServerWebExchange exchange, String path) {
    try {//  w ww.ja v a 2s.  com
        Token token = getToken(exchange.getRequest());
        return this.tokenValidator.validate(token)
                .then(this.cloudFoundrySecurityService.getAccessLevel(token.toString(), this.applicationId))
                .filter((accessLevel) -> accessLevel.isAccessAllowed(path))
                .switchIfEmpty(Mono
                        .error(new CloudFoundryAuthorizationException(Reason.ACCESS_DENIED, "Access denied")))
                .doOnSuccess(
                        (accessLevel) -> exchange.getAttributes().put("cloudFoundryAccessLevel", accessLevel))
                .then();
    } catch (CloudFoundryAuthorizationException ex) {
        return Mono.error(ex);
    }
}

From source file:org.springframework.cloud.gateway.filter.factory.RetryGatewayFilterFactory.java

public void reset(ServerWebExchange exchange) {
    // TODO: what else to do to reset SWE?
    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);
}

From source file:org.springframework.cloud.gateway.filter.LoadBalancerClientFilter.java

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    URI url = getAttribute(exchange, GATEWAY_REQUEST_URL_ATTR, URI.class);
    if (url == null || !url.getScheme().equals("lb")) {
        return chain.filter(exchange);
    }//from  w w w  .j a v a2s.  co  m
    log.trace("LoadBalancerClientFilter url before: " + url);

    final ServiceInstance instance = loadBalancer.choose(url.getHost());

    if (instance == null) {
        throw new NotFoundException("");
    }

    URI requestUrl = UriComponentsBuilder.fromUri(url).scheme(instance.isSecure() ? "https" : "http") //TODO: support websockets
            .host(instance.getHost()).port(instance.getPort()).build(true).toUri();
    log.trace("LoadBalancerClientFilter url chosen: " + requestUrl);
    exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUrl);
    return chain.filter(exchange);
}

From source file:org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter.java

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    Route route = getAttribute(exchange, GATEWAY_ROUTE_ATTR, Route.class);
    if (route == null) {
        return chain.filter(exchange);
    }//w w w  . jav a2s. c o  m
    log.info("RouteToRequestUrlFilter start");
    URI requestUrl = UriComponentsBuilder.fromHttpRequest(exchange.getRequest()).uri(route.getUri()).build(true)
            .toUri();
    exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUrl);
    return chain.filter(exchange);
}

From source file:org.springframework.cloud.gateway.filter.WebsocketRoutingFilter.java

private void changeSchemeIfIsWebSocketUpgrade(ServerWebExchange exchange) {
    // Check the Upgrade
    URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
    String scheme = requestUrl.getScheme().toLowerCase();
    String upgrade = exchange.getRequest().getHeaders().getUpgrade();
    // change the scheme if the socket client send a "http" or "https"
    if ("WebSocket".equalsIgnoreCase(upgrade) && ("http".equals(scheme) || "https".equals(scheme))) {
        String wsScheme = convertHttpToWs(scheme);
        URI wsRequestUrl = UriComponentsBuilder.fromUri(requestUrl).scheme(wsScheme).build().toUri();
        exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, wsRequestUrl);
        if (log.isTraceEnabled()) {
            log.trace("changeSchemeTo:[" + wsRequestUrl + "]");
        }//from   w w  w.ja v a2s. c o  m
    }
}

From source file:org.springframework.cloud.gateway.filter.WeightCalculatorWebFilter.java

static Map<String, String> getWeights(ServerWebExchange exchange) {
    Map<String, String> weights = exchange.getAttribute(WEIGHT_ATTR);

    if (weights == null) {
        weights = new ConcurrentHashMap<>();
        exchange.getAttributes().put(WEIGHT_ATTR, weights);
    }/*from  ww  w. j  a va2  s.  c  o m*/
    return weights;
}

From source file:org.springframework.cloud.gateway.support.ServerWebExchangeUtils.java

public static <T> T getAttribute(ServerWebExchange exchange, String attributeName, Class<T> type) {
    if (exchange.getAttributes().containsKey(attributeName)) {
        Object attr = exchange.getAttributes().get(attributeName);
        if (type.isAssignableFrom(attr.getClass())) {
            return type.cast(attr);
        }/*from   www  . j  a  va  2  s .c o  m*/
        throw new ClassCastException(attributeName + " is not of type " + type);
    }
    return null;
}

From source file:org.springframework.cloud.sleuth.instrument.web.TraceWebFilter.java

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    if (tracer().currentSpan() != null) {
        // clear any previous trace
        tracer().withSpanInScope(null);//ww  w.ja  v  a 2 s . com
    }
    String uri = exchange.getRequest().getPath().pathWithinApplication().value();
    if (log.isDebugEnabled()) {
        log.debug("Received a request to uri [" + uri + "]");
    }
    Span spanFromAttribute = getSpanFromAttribute(exchange);
    final String CONTEXT_ERROR = "sleuth.webfilter.context.error";
    return chain.filter(exchange).compose(f -> f.then(Mono.subscriberContext())
            .onErrorResume(t -> Mono.subscriberContext().map(c -> c.put(CONTEXT_ERROR, t))).flatMap(c -> {
                // reactivate span from context
                Span span = spanFromContext(c);
                Mono<Void> continuation;
                Throwable t = null;
                if (c.hasKey(CONTEXT_ERROR)) {
                    t = c.get(CONTEXT_ERROR);
                    continuation = Mono.error(t);
                } else {
                    continuation = Mono.empty();
                }
                String httpRoute = null;
                Object attribute = exchange.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE);
                if (attribute instanceof HandlerMethod) {
                    HandlerMethod handlerMethod = (HandlerMethod) attribute;
                    addClassMethodTag(handlerMethod, span);
                    addClassNameTag(handlerMethod, span);
                    Object pattern = exchange.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
                    httpRoute = pattern != null ? pattern.toString() : "";
                }
                addResponseTagsForSpanWithoutParent(exchange, exchange.getResponse(), span);
                DecoratedServerHttpResponse delegate = new DecoratedServerHttpResponse(exchange.getResponse(),
                        exchange.getRequest().getMethodValue(), httpRoute);
                handler().handleSend(delegate, t, span);
                if (log.isDebugEnabled()) {
                    log.debug("Handled send of " + span);
                }
                return continuation;
            }).subscriberContext(c -> {
                Span span;
                if (c.hasKey(Span.class)) {
                    Span parent = c.get(Span.class);
                    span = tracer().nextSpan(TraceContextOrSamplingFlags.create(parent.context())).start();
                    if (log.isDebugEnabled()) {
                        log.debug("Found span in reactor context" + span);
                    }
                } else {
                    if (spanFromAttribute != null) {
                        span = spanFromAttribute;
                        if (log.isDebugEnabled()) {
                            log.debug("Found span in attribute " + span);
                        }
                    } else {
                        span = handler().handleReceive(extractor(), exchange.getRequest().getHeaders(),
                                exchange.getRequest());
                        if (log.isDebugEnabled()) {
                            log.debug("Handled receive of span " + span);
                        }
                    }
                    exchange.getAttributes().put(TRACE_REQUEST_ATTR, span);
                }
                return c.put(Span.class, span);
            }));
}

From source file:org.springframework.web.reactive.function.server.RouterFunctions.java

private static void addAttributes(ServerWebExchange exchange, ServerRequest request) {
    Map<String, Object> attributes = exchange.getAttributes();
    attributes.put(REQUEST_ATTRIBUTE, request);
}