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

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

Introduction

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

Prototype

ServerHttpRequest getRequest();

Source Link

Document

Return the current HTTP request.

Usage

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

Mono<SecurityResponse> preHandle(ServerWebExchange exchange, String endpointId) {
    ServerHttpRequest request = exchange.getRequest();
    if (CorsUtils.isPreFlightRequest(request)) {
        return SUCCESS;
    }//w w  w  .  ja  v a2s.com
    if (!StringUtils.hasText(this.applicationId)) {
        return Mono.error(new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE,
                "Application id is not available"));
    }
    if (this.cloudFoundrySecurityService == null) {
        return Mono.error(new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE,
                "Cloud controller URL is not available"));
    }
    return check(exchange, endpointId).then(SUCCESS).doOnError(this::logError)
            .onErrorResume(this::getErrorResponse);
}

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

private Mono<Void> check(ServerWebExchange exchange, String path) {
    try {/* www  . j a  v a2  s. c o m*/
        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.function.web.RequestProcessor.java

private Publisher<?> body(Object handler, ServerWebExchange exchange) {
    ResolvableType elementType = ResolvableType.forClass(this.inspector.getInputType(handler));
    ResolvableType actualType = elementType;
    Class<?> resolvedType = elementType.resolve();
    ReactiveAdapter adapter = (resolvedType != null ? getAdapterRegistry().getAdapter(resolvedType) : null);

    ServerHttpRequest request = exchange.getRequest();
    ServerHttpResponse response = exchange.getResponse();

    MediaType contentType = request.getHeaders().getContentType();
    MediaType mediaType = (contentType != null ? contentType : MediaType.APPLICATION_OCTET_STREAM);

    if (logger.isDebugEnabled()) {
        logger.debug(exchange.getLogPrefix() + (contentType != null ? "Content-Type:" + contentType
                : "No Content-Type, using " + MediaType.APPLICATION_OCTET_STREAM));
    }/*from  w w  w  . j a v  a  2  s.  com*/
    boolean isBodyRequired = (adapter != null && !adapter.supportsEmpty());

    MethodParameter bodyParam = new MethodParameter(handlerMethod(handler), 0);
    for (HttpMessageReader<?> reader : getMessageReaders()) {
        if (reader.canRead(elementType, mediaType)) {
            Map<String, Object> readHints = Hints.from(Hints.LOG_PREFIX_HINT, exchange.getLogPrefix());
            if (adapter != null && adapter.isMultiValue()) {
                if (logger.isDebugEnabled()) {
                    logger.debug(exchange.getLogPrefix() + "0..N [" + elementType + "]");
                }
                Flux<?> flux = reader.read(actualType, elementType, request, response, readHints);
                flux = flux.onErrorResume(ex -> Flux.error(handleReadError(bodyParam, ex)));
                if (isBodyRequired) {
                    flux = flux.switchIfEmpty(Flux.error(() -> handleMissingBody(bodyParam)));
                }
                return Mono.just(adapter.fromPublisher(flux));
            } else {
                // Single-value (with or without reactive type wrapper)
                if (logger.isDebugEnabled()) {
                    logger.debug(exchange.getLogPrefix() + "0..1 [" + elementType + "]");
                }
                Mono<?> mono = reader.readMono(actualType, elementType, request, response, readHints);
                mono = mono.onErrorResume(ex -> Mono.error(handleReadError(bodyParam, ex)));
                if (isBodyRequired) {
                    mono = mono.switchIfEmpty(Mono.error(() -> handleMissingBody(bodyParam)));
                }
                return (adapter != null ? Mono.just(adapter.fromPublisher(mono)) : Mono.from(mono));
            }
        }
    }

    return Mono.error(new UnsupportedMediaTypeStatusException(mediaType,
            Arrays.asList(MediaType.APPLICATION_JSON), elementType));
}

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

@Override
public GatewayFilter apply(RetryConfig retryConfig) {
    retryConfig.validate();/*from   w  w  w  .  j a v a2  s  .c o m*/

    Repeat<ServerWebExchange> statusCodeRepeat = null;
    if (!retryConfig.getStatuses().isEmpty() || !retryConfig.getSeries().isEmpty()) {
        Predicate<RepeatContext<ServerWebExchange>> repeatPredicate = context -> {
            ServerWebExchange exchange = context.applicationContext();
            if (exceedsMaxIterations(exchange, retryConfig)) {
                return false;
            }

            HttpStatus statusCode = exchange.getResponse().getStatusCode();

            boolean retryableStatusCode = retryConfig.getStatuses().contains(statusCode);

            if (!retryableStatusCode && statusCode != null) { // null status code
                // might mean a
                // network exception?
                // try the series
                retryableStatusCode = retryConfig.getSeries().stream()
                        .anyMatch(series -> statusCode.series().equals(series));
            }

            trace("retryableStatusCode: %b, statusCode %s, configured statuses %s, configured series %s",
                    retryableStatusCode, statusCode, retryConfig.getStatuses(), retryConfig.getSeries());

            HttpMethod httpMethod = exchange.getRequest().getMethod();
            boolean retryableMethod = retryConfig.getMethods().contains(httpMethod);

            trace("retryableMethod: %b, httpMethod %s, configured methods %s", retryableMethod, httpMethod,
                    retryConfig.getMethods());
            return retryableMethod && retryableStatusCode;
        };

        statusCodeRepeat = Repeat.onlyIf(repeatPredicate)
                .doOnRepeat(context -> reset(context.applicationContext()));
    }

    // TODO: support timeout, backoff, jitter, etc... in Builder

    Retry<ServerWebExchange> exceptionRetry = null;
    if (!retryConfig.getExceptions().isEmpty()) {
        Predicate<RetryContext<ServerWebExchange>> retryContextPredicate = context -> {
            if (exceedsMaxIterations(context.applicationContext(), retryConfig)) {
                return false;
            }

            for (Class<? extends Throwable> clazz : retryConfig.getExceptions()) {
                if (clazz.isInstance(context.exception())) {
                    trace("exception is retryable %s, configured exceptions",
                            context.exception().getClass().getName(), retryConfig.getExceptions());
                    return true;
                }
            }
            trace("exception is not retryable %s, configured exceptions",
                    context.exception().getClass().getName(), retryConfig.getExceptions());
            return false;
        };
        exceptionRetry = Retry.onlyIf(retryContextPredicate)
                .doOnRetry(context -> reset(context.applicationContext())).retryMax(retryConfig.getRetries());
    }

    return apply(statusCodeRepeat, exceptionRetry);
}

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);
    }/*from   w ww.  ja v  a 2  s  . co  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

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    changeSchemeIfIsWebSocketUpgrade(exchange);

    URI requestUrl = exchange.getRequiredAttribute(GATEWAY_REQUEST_URL_ATTR);
    String scheme = requestUrl.getScheme();

    if (isAlreadyRouted(exchange) || (!"ws".equals(scheme) && !"wss".equals(scheme))) {
        return chain.filter(exchange);
    }//  ww  w . ja  v  a2  s  .  c  om
    setAlreadyRouted(exchange);

    HttpHeaders headers = exchange.getRequest().getHeaders();
    HttpHeaders filtered = filterRequest(getHeadersFilters(), exchange);

    List<String> protocols = headers.get(SEC_WEBSOCKET_PROTOCOL);
    if (protocols != null) {
        protocols = headers.get(SEC_WEBSOCKET_PROTOCOL).stream()
                .flatMap(header -> Arrays.stream(commaDelimitedListToStringArray(header))).map(String::trim)
                .collect(Collectors.toList());
    }

    return this.webSocketService.handleRequest(exchange,
            new ProxyWebSocketHandler(requestUrl, this.webSocketClient, filtered, protocols));
}

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 .  j  av a 2  s. c o  m*/
    }
}

From source file:org.springframework.cloud.gateway.test.HttpBinCompatibleController.java

@RequestMapping(path = "/get", produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String, Object> get(ServerWebExchange exchange) {
    if (log.isDebugEnabled()) {
        log.debug("httpbin /get");
    }/*from   w  ww  . j a  v a2s .c  o m*/
    HashMap<String, Object> result = new HashMap<>();
    HashMap<String, String> params = new HashMap<>();
    exchange.getRequest().getQueryParams().forEach((name, values) -> {
        params.put(name, values.get(0));
    });
    result.put("args", params);
    result.put("headers", getHeaders(exchange));
    return result;
}

From source file:org.springframework.cloud.gateway.test.HttpBinCompatibleController.java

public Map<String, String> getHeaders(ServerWebExchange exchange) {
    return exchange.getRequest().getHeaders().toSingleValueMap();
}

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);//from   w w w .j  a  va  2  s  .c o  m
    }
    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);
            }));
}