Search in sources :

Example 1 with ServerHttpRequest

use of org.springframework.http.server.reactive.ServerHttpRequest in project spring-framework by spring-projects.

the class RequestMappingInfoHandlerMapping method handleNoMatch.

/**
	 * Iterate all RequestMappingInfos once again, look if any match by URL at
	 * least and raise exceptions accordingly.
	 * @throws MethodNotAllowedException for matches by URL but not by HTTP method
	 * @throws UnsupportedMediaTypeStatusException if there are matches by URL
	 * and HTTP method but not by consumable media types
	 * @throws NotAcceptableStatusException if there are matches by URL and HTTP
	 * method but not by producible media types
	 * @throws ServerWebInputException if there are matches by URL and HTTP
	 * method but not by query parameter conditions
	 */
@Override
protected HandlerMethod handleNoMatch(Set<RequestMappingInfo> infos, String lookupPath, ServerWebExchange exchange) throws Exception {
    PartialMatchHelper helper = new PartialMatchHelper(infos, exchange);
    if (helper.isEmpty()) {
        return null;
    }
    ServerHttpRequest request = exchange.getRequest();
    if (helper.hasMethodsMismatch()) {
        HttpMethod httpMethod = request.getMethod();
        Set<String> methods = helper.getAllowedMethods();
        if (HttpMethod.OPTIONS.matches(httpMethod.name())) {
            HttpOptionsHandler handler = new HttpOptionsHandler(methods);
            return new HandlerMethod(handler, HTTP_OPTIONS_HANDLE_METHOD);
        }
        throw new MethodNotAllowedException(httpMethod.name(), methods);
    }
    if (helper.hasConsumesMismatch()) {
        Set<MediaType> mediaTypes = helper.getConsumableMediaTypes();
        MediaType contentType;
        try {
            contentType = request.getHeaders().getContentType();
        } catch (InvalidMediaTypeException ex) {
            throw new UnsupportedMediaTypeStatusException(ex.getMessage());
        }
        throw new UnsupportedMediaTypeStatusException(contentType, new ArrayList<>(mediaTypes));
    }
    if (helper.hasProducesMismatch()) {
        Set<MediaType> mediaTypes = helper.getProducibleMediaTypes();
        throw new NotAcceptableStatusException(new ArrayList<>(mediaTypes));
    }
    if (helper.hasParamsMismatch()) {
        throw new ServerWebInputException("Unsatisfied query parameter conditions: " + helper.getParamConditions() + ", actual parameters: " + request.getQueryParams());
    }
    return null;
}
Also used : NotAcceptableStatusException(org.springframework.web.server.NotAcceptableStatusException) ServerWebInputException(org.springframework.web.server.ServerWebInputException) MethodNotAllowedException(org.springframework.web.server.MethodNotAllowedException) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) HandlerMethod(org.springframework.web.method.HandlerMethod) UnsupportedMediaTypeStatusException(org.springframework.web.server.UnsupportedMediaTypeStatusException) MediaType(org.springframework.http.MediaType) HttpMethod(org.springframework.http.HttpMethod) InvalidMediaTypeException(org.springframework.http.InvalidMediaTypeException)

Example 2 with ServerHttpRequest

use of org.springframework.http.server.reactive.ServerHttpRequest in project spring-framework by spring-projects.

the class RxNettyRequestUpgradeStrategy method getHandshakeInfo.

private HandshakeInfo getHandshakeInfo(ServerWebExchange exchange, Optional<String> protocol) {
    ServerHttpRequest request = exchange.getRequest();
    Mono<Principal> principal = exchange.getPrincipal();
    return new HandshakeInfo(request.getURI(), request.getHeaders(), principal, protocol);
}
Also used : ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) Principal(java.security.Principal) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo)

Example 3 with ServerHttpRequest

use of org.springframework.http.server.reactive.ServerHttpRequest in project spring-framework by spring-projects.

the class UndertowRequestUpgradeStrategy method upgrade.

@Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, Optional<String> subProtocol) {
    ServerHttpRequest request = exchange.getRequest();
    Assert.isInstanceOf(UndertowServerHttpRequest.class, request, "UndertowServerHttpRequest required");
    HttpServerExchange httpExchange = ((UndertowServerHttpRequest) request).getUndertowExchange();
    Set<String> protocols = subProtocol.map(Collections::singleton).orElse(Collections.emptySet());
    Hybi13Handshake handshake = new Hybi13Handshake(protocols, false);
    List<Handshake> handshakes = Collections.singletonList(handshake);
    URI url = request.getURI();
    HttpHeaders headers = request.getHeaders();
    Mono<Principal> principal = exchange.getPrincipal();
    HandshakeInfo info = new HandshakeInfo(url, headers, principal, subProtocol);
    DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory();
    try {
        DefaultCallback callback = new DefaultCallback(info, handler, bufferFactory);
        new WebSocketProtocolHandshakeHandler(handshakes, callback).handleRequest(httpExchange);
    } catch (Exception ex) {
        return Mono.error(ex);
    }
    return Mono.empty();
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) Hybi13Handshake(io.undertow.websockets.core.protocol.version13.Hybi13Handshake) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) UndertowServerHttpRequest(org.springframework.http.server.reactive.UndertowServerHttpRequest) URI(java.net.URI) HttpServerExchange(io.undertow.server.HttpServerExchange) WebSocketProtocolHandshakeHandler(io.undertow.websockets.WebSocketProtocolHandshakeHandler) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) UndertowServerHttpRequest(org.springframework.http.server.reactive.UndertowServerHttpRequest) Principal(java.security.Principal) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo) Hybi13Handshake(io.undertow.websockets.core.protocol.version13.Hybi13Handshake) Handshake(io.undertow.websockets.core.protocol.Handshake)

Example 4 with ServerHttpRequest

use of org.springframework.http.server.reactive.ServerHttpRequest in project spring-cloud-sleuth by spring-cloud.

the class TraceWebFilter method filter.

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    if (tracer().currentSpan() != null) {
        // clear any previous trace
        tracer().withSpanInScope(null);
    }
    ServerHttpRequest request = exchange.getRequest();
    ServerHttpResponse response = exchange.getResponse();
    String uri = request.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();
        }
        Object attribute = exchange.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE);
        if (attribute instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) attribute;
            addClassMethodTag(handlerMethod, span);
            addClassNameTag(handlerMethod, span);
        }
        addResponseTagsForSpanWithoutParent(exchange, response, span);
        handler().handleSend(response, 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(), request.getHeaders(), request);
                if (log.isDebugEnabled()) {
                    log.debug("Handled receive of span " + span);
                }
            }
            exchange.getAttributes().put(TRACE_REQUEST_ATTR, span);
        }
        return c.put(Span.class, span);
    }));
}
Also used : HttpTracing(brave.http.HttpTracing) Ordered(org.springframework.core.Ordered) Tracer(brave.Tracer) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) TraceContextOrSamplingFlags(brave.propagation.TraceContextOrSamplingFlags) HttpHeaders(org.springframework.http.HttpHeaders) Context(reactor.util.context.Context) Span(brave.Span) Mono(reactor.core.publisher.Mono) TraceContext(brave.propagation.TraceContext) ServerWebExchange(org.springframework.web.server.ServerWebExchange) TraceKeys(org.springframework.cloud.sleuth.TraceKeys) HandlerMethod(org.springframework.web.method.HandlerMethod) WebFilter(org.springframework.web.server.WebFilter) BeanFactory(org.springframework.beans.factory.BeanFactory) Propagation(brave.propagation.Propagation) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) HttpServerHandler(brave.http.HttpServerHandler) HandlerMapping(org.springframework.web.reactive.HandlerMapping) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) WebFilterChain(org.springframework.web.server.WebFilterChain) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) Span(brave.Span) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) HandlerMethod(org.springframework.web.method.HandlerMethod)

Example 5 with ServerHttpRequest

use of org.springframework.http.server.reactive.ServerHttpRequest in project spring-integration by spring-projects.

the class WebFluxInboundEndpoint method buildMessage.

@SuppressWarnings("unchecked")
private Message<?> buildMessage(HttpEntity<?> httpEntity, ServerWebExchange exchange) {
    ServerHttpRequest request = exchange.getRequest();
    HttpHeaders requestHeaders = request.getHeaders();
    Map<String, Object> exchangeAttributes = exchange.getAttributes();
    StandardEvaluationContext evaluationContext = createEvaluationContext();
    evaluationContext.setVariable("requestAttributes", exchangeAttributes);
    MultiValueMap<String, String> requestParams = request.getQueryParams();
    evaluationContext.setVariable("requestParams", requestParams);
    evaluationContext.setVariable("requestHeaders", requestHeaders);
    if (!CollectionUtils.isEmpty(request.getCookies())) {
        evaluationContext.setVariable("cookies", request.getCookies());
    }
    Map<String, String> pathVariables = (Map<String, String>) exchangeAttributes.get(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
    if (!CollectionUtils.isEmpty(pathVariables)) {
        evaluationContext.setVariable("pathVariables", pathVariables);
    }
    Map<String, MultiValueMap<String, String>> matrixVariables = (Map<String, MultiValueMap<String, String>>) exchangeAttributes.get(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE);
    if (!CollectionUtils.isEmpty(matrixVariables)) {
        evaluationContext.setVariable("matrixVariables", matrixVariables);
    }
    evaluationContext.setRootObject(httpEntity);
    Object payload;
    if (getPayloadExpression() != null) {
        payload = getPayloadExpression().getValue(evaluationContext);
        if (payload == null) {
            throw new IllegalStateException("The payload expression '" + getPayloadExpression().getExpressionString() + "' returned null.");
        }
    } else {
        payload = httpEntity.getBody();
    }
    Map<String, Object> headers = getHeaderMapper().toHeaders(request.getHeaders());
    if (!CollectionUtils.isEmpty(getHeaderExpressions())) {
        for (Map.Entry<String, Expression> entry : getHeaderExpressions().entrySet()) {
            String headerName = entry.getKey();
            Expression headerExpression = entry.getValue();
            Object headerValue = headerExpression.getValue(evaluationContext);
            if (headerValue != null) {
                headers.put(headerName, headerValue);
            }
        }
    }
    AbstractIntegrationMessageBuilder<?> messageBuilder;
    if (payload instanceof Message<?>) {
        messageBuilder = getMessageBuilderFactory().fromMessage((Message<?>) payload).copyHeadersIfAbsent(headers);
    } else {
        messageBuilder = getMessageBuilderFactory().withPayload(payload).copyHeaders(headers);
    }
    return messageBuilder.setHeader(org.springframework.integration.http.HttpHeaders.REQUEST_URL, request.getURI().toString()).setHeader(org.springframework.integration.http.HttpHeaders.REQUEST_METHOD, request.getMethod().toString()).setHeader(org.springframework.integration.http.HttpHeaders.USER_PRINCIPAL, exchange.getPrincipal().block()).build();
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) Message(org.springframework.messaging.Message) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) Expression(org.springframework.expression.Expression) Map(java.util.Map) MultiValueMap(org.springframework.util.MultiValueMap) MultiValueMap(org.springframework.util.MultiValueMap)

Aggregations

ServerHttpRequest (org.springframework.http.server.reactive.ServerHttpRequest)71 HttpHeaders (org.springframework.http.HttpHeaders)26 Test (org.junit.jupiter.api.Test)25 MockServerHttpRequest (org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest)20 ServerWebExchange (org.springframework.web.server.ServerWebExchange)19 URI (java.net.URI)17 ServerHttpResponse (org.springframework.http.server.reactive.ServerHttpResponse)17 Mono (reactor.core.publisher.Mono)13 MockServerHttpRequest (org.springframework.mock.http.server.reactive.MockServerHttpRequest)10 HandshakeInfo (org.springframework.web.reactive.socket.HandshakeInfo)9 HttpMethod (org.springframework.http.HttpMethod)8 ArrayList (java.util.ArrayList)7 List (java.util.List)6 Map (java.util.Map)6 HttpStatus (org.springframework.http.HttpStatus)6 MediaType (org.springframework.http.MediaType)6 Flux (reactor.core.publisher.Flux)6 Principal (java.security.Principal)5 Collections (java.util.Collections)5 HashMap (java.util.HashMap)5