Search in sources :

Example 11 with ServerHttpResponse

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

the class BodyInsertersTests method ofServerSentEventFlux.

@Test
public void ofServerSentEventFlux() throws Exception {
    ServerSentEvent<String> event = ServerSentEvent.builder("foo").build();
    Flux<ServerSentEvent<String>> body = Flux.just(event);
    BodyInserter<Flux<ServerSentEvent<String>>, ServerHttpResponse> inserter = BodyInserters.fromServerSentEvents(body);
    MockServerHttpResponse response = new MockServerHttpResponse();
    Mono<Void> result = inserter.insert(response, this.context);
    StepVerifier.create(result).expectNextCount(0).expectComplete().verify();
}
Also used : ServerSentEvent(org.springframework.http.codec.ServerSentEvent) Flux(reactor.core.publisher.Flux) MockServerHttpResponse(org.springframework.mock.http.server.reactive.test.MockServerHttpResponse) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) MockServerHttpResponse(org.springframework.mock.http.server.reactive.test.MockServerHttpResponse) Test(org.junit.Test)

Example 12 with ServerHttpResponse

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

the class AbstractMessageReaderArgumentResolver method readBody.

protected Mono<Object> readBody(MethodParameter bodyParameter, boolean isBodyRequired, BindingContext bindingContext, ServerWebExchange exchange) {
    ResolvableType bodyType = ResolvableType.forMethodParameter(bodyParameter);
    ReactiveAdapter adapter = getAdapterRegistry().getAdapter(bodyType.resolve());
    ResolvableType elementType = (adapter != null ? bodyType.getGeneric(0) : bodyType);
    ServerHttpRequest request = exchange.getRequest();
    ServerHttpResponse response = exchange.getResponse();
    MediaType mediaType = request.getHeaders().getContentType();
    if (mediaType == null) {
        mediaType = MediaType.APPLICATION_OCTET_STREAM;
    }
    for (HttpMessageReader<?> reader : getMessageReaders()) {
        if (reader.canRead(elementType, mediaType)) {
            Map<String, Object> readHints = Collections.emptyMap();
            if (adapter != null && adapter.isMultiValue()) {
                Flux<?> flux;
                if (reader instanceof ServerHttpMessageReader) {
                    ServerHttpMessageReader<?> serverReader = ((ServerHttpMessageReader<?>) reader);
                    flux = serverReader.read(bodyType, elementType, request, response, readHints);
                } else {
                    flux = reader.read(elementType, request, readHints);
                }
                flux = flux.onErrorResumeWith(ex -> Flux.error(getReadError(bodyParameter, ex)));
                if (isBodyRequired || !adapter.supportsEmpty()) {
                    flux = flux.switchIfEmpty(Flux.error(getRequiredBodyError(bodyParameter)));
                }
                Object[] hints = extractValidationHints(bodyParameter);
                if (hints != null) {
                    flux = flux.doOnNext(target -> validate(target, hints, bodyParameter, bindingContext, exchange));
                }
                return Mono.just(adapter.fromPublisher(flux));
            } else {
                Mono<?> mono;
                if (reader instanceof ServerHttpMessageReader) {
                    ServerHttpMessageReader<?> serverReader = (ServerHttpMessageReader<?>) reader;
                    mono = serverReader.readMono(bodyType, elementType, request, response, readHints);
                } else {
                    mono = reader.readMono(elementType, request, readHints);
                }
                mono = mono.otherwise(ex -> Mono.error(getReadError(bodyParameter, ex)));
                if (isBodyRequired || (adapter != null && !adapter.supportsEmpty())) {
                    mono = mono.otherwiseIfEmpty(Mono.error(getRequiredBodyError(bodyParameter)));
                }
                Object[] hints = extractValidationHints(bodyParameter);
                if (hints != null) {
                    mono = mono.doOnNext(target -> validate(target, hints, bodyParameter, bindingContext, exchange));
                }
                if (adapter != null) {
                    return Mono.just(adapter.fromPublisher(mono));
                } else {
                    return Mono.from(mono);
                }
            }
        }
    }
    return Mono.error(new UnsupportedMediaTypeStatusException(mediaType, this.supportedMediaTypes));
}
Also used : ServerHttpMessageReader(org.springframework.http.codec.ServerHttpMessageReader) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) Validator(org.springframework.validation.Validator) Conventions(org.springframework.core.Conventions) WebExchangeDataBinder(org.springframework.web.bind.support.WebExchangeDataBinder) ServerWebInputException(org.springframework.web.server.ServerWebInputException) HttpMessageReader(org.springframework.http.codec.HttpMessageReader) BindingContext(org.springframework.web.reactive.BindingContext) ServerWebExchange(org.springframework.web.server.ServerWebExchange) HandlerMethodArgumentResolverSupport(org.springframework.web.reactive.result.method.HandlerMethodArgumentResolverSupport) UnsupportedMediaTypeStatusException(org.springframework.web.server.UnsupportedMediaTypeStatusException) Map(java.util.Map) MethodParameter(org.springframework.core.MethodParameter) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) WebExchangeBindException(org.springframework.web.bind.support.WebExchangeBindException) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) ReactiveAdapter(org.springframework.core.ReactiveAdapter) Validated(org.springframework.validation.annotation.Validated) AnnotationUtils(org.springframework.core.annotation.AnnotationUtils) MediaType(org.springframework.http.MediaType) Mono(reactor.core.publisher.Mono) Collectors(java.util.stream.Collectors) Flux(reactor.core.publisher.Flux) List(java.util.List) Annotation(java.lang.annotation.Annotation) Collections(java.util.Collections) Assert(org.springframework.util.Assert) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) ServerHttpMessageReader(org.springframework.http.codec.ServerHttpMessageReader) UnsupportedMediaTypeStatusException(org.springframework.web.server.UnsupportedMediaTypeStatusException) MediaType(org.springframework.http.MediaType) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapter(org.springframework.core.ReactiveAdapter)

Example 13 with ServerHttpResponse

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

the class JettyRequestUpgradeStrategy method upgrade.

@Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, Optional<String> subProtocol) {
    ServerHttpRequest request = exchange.getRequest();
    ServerHttpResponse response = exchange.getResponse();
    HttpServletRequest servletRequest = getHttpServletRequest(request);
    HttpServletResponse servletResponse = getHttpServletResponse(response);
    JettyWebSocketHandlerAdapter adapter = new JettyWebSocketHandlerAdapter(handler, session -> {
        HandshakeInfo info = getHandshakeInfo(exchange, subProtocol);
        DataBufferFactory factory = response.bufferFactory();
        return new JettyWebSocketSession(session, info, factory);
    });
    startLazily(servletRequest);
    boolean isUpgrade = this.factory.isUpgradeRequest(servletRequest, servletResponse);
    Assert.isTrue(isUpgrade, "Not a WebSocket handshake");
    try {
        adapterHolder.set(new WebSocketHandlerContainer(adapter, subProtocol));
        this.factory.acceptWebSocket(servletRequest, servletResponse);
    } catch (IOException ex) {
        return Mono.error(ex);
    } finally {
        adapterHolder.remove();
    }
    return Mono.empty();
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletServerHttpRequest(org.springframework.http.server.reactive.ServletServerHttpRequest) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) JettyWebSocketSession(org.springframework.web.reactive.socket.adapter.JettyWebSocketSession) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) ServletServerHttpResponse(org.springframework.http.server.reactive.ServletServerHttpResponse) JettyWebSocketHandlerAdapter(org.springframework.web.reactive.socket.adapter.JettyWebSocketHandlerAdapter) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo)

Example 14 with ServerHttpResponse

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

the class HttpMessageWriterView method applyMessageWriter.

@SuppressWarnings("unchecked")
private <T> Mono<Void> applyMessageWriter(Object value, MediaType contentType, ServerWebExchange exchange) {
    if (value == null) {
        return Mono.empty();
    }
    Publisher<? extends T> stream = Mono.just((T) value);
    ResolvableType type = ResolvableType.forClass(value.getClass());
    ServerHttpResponse response = exchange.getResponse();
    return ((HttpMessageWriter<T>) getMessageWriter()).write(stream, type, contentType, response, Collections.emptyMap());
}
Also used : EncoderHttpMessageWriter(org.springframework.http.codec.EncoderHttpMessageWriter) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) ResolvableType(org.springframework.core.ResolvableType) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse)

Example 15 with ServerHttpResponse

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

the class ScriptTemplateView method renderInternal.

@Override
protected Mono<Void> renderInternal(Map<String, Object> model, MediaType contentType, ServerWebExchange exchange) {
    return Mono.defer(() -> {
        ServerHttpResponse response = exchange.getResponse();
        try {
            ScriptEngine engine = getEngine();
            Invocable invocable = (Invocable) engine;
            String url = getUrl();
            String template = getTemplate(url);
            Function<String, String> templateLoader = path -> {
                try {
                    return getTemplate(path);
                } catch (IOException ex) {
                    throw new IllegalStateException(ex);
                }
            };
            RenderingContext context = new RenderingContext(this.getApplicationContext(), this.locale, templateLoader, url);
            Object html;
            if (this.renderObject != null) {
                Object thiz = engine.eval(this.renderObject);
                html = invocable.invokeMethod(thiz, this.renderFunction, template, model, context);
            } else {
                html = invocable.invokeFunction(this.renderFunction, template, model, context);
            }
            byte[] bytes = String.valueOf(html).getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().allocateBuffer(bytes.length).write(bytes);
            return response.writeWith(Mono.just(buffer));
        } catch (ScriptException ex) {
            throw new IllegalStateException("Failed to render script template", new StandardScriptEvalException(ex));
        } catch (Exception ex) {
            throw new IllegalStateException("Failed to render script template", ex);
        }
    });
}
Also used : ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) BeanFactoryUtils(org.springframework.beans.factory.BeanFactoryUtils) ApplicationContextException(org.springframework.context.ApplicationContextException) Function(java.util.function.Function) StandardScriptUtils(org.springframework.scripting.support.StandardScriptUtils) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Locale(java.util.Locale) Map(java.util.Map) ScriptException(javax.script.ScriptException) Resource(org.springframework.core.io.Resource) AbstractUrlBasedView(org.springframework.web.reactive.result.view.AbstractUrlBasedView) ResourceLoader(org.springframework.core.io.ResourceLoader) MediaType(org.springframework.http.MediaType) ObjectUtils(org.springframework.util.ObjectUtils) ScriptEngineManager(javax.script.ScriptEngineManager) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) BeansException(org.springframework.beans.BeansException) DataBuffer(org.springframework.core.io.buffer.DataBuffer) InputStreamReader(java.io.InputStreamReader) ApplicationContext(org.springframework.context.ApplicationContext) StandardCharsets(java.nio.charset.StandardCharsets) Invocable(javax.script.Invocable) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) ScriptEngine(javax.script.ScriptEngine) StandardScriptEvalException(org.springframework.scripting.support.StandardScriptEvalException) FileCopyUtils(org.springframework.util.FileCopyUtils) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) IOException(java.io.IOException) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) ScriptEngine(javax.script.ScriptEngine) ApplicationContextException(org.springframework.context.ApplicationContextException) ScriptException(javax.script.ScriptException) IOException(java.io.IOException) BeansException(org.springframework.beans.BeansException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) StandardScriptEvalException(org.springframework.scripting.support.StandardScriptEvalException) Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException) StandardScriptEvalException(org.springframework.scripting.support.StandardScriptEvalException) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Aggregations

ServerHttpResponse (org.springframework.http.server.reactive.ServerHttpResponse)30 Test (org.junit.Test)21 ServerWebExchange (org.springframework.web.server.ServerWebExchange)20 ServerHttpRequest (org.springframework.http.server.reactive.ServerHttpRequest)6 ResolvableType (org.springframework.core.ResolvableType)4 MediaType (org.springframework.http.MediaType)4 Flux (reactor.core.publisher.Flux)4 IOException (java.io.IOException)3 Collections (java.util.Collections)3 Mono (reactor.core.publisher.Mono)3 List (java.util.List)2 Map (java.util.Map)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 ReactiveAdapter (org.springframework.core.ReactiveAdapter)2 DataBufferFactory (org.springframework.core.io.buffer.DataBufferFactory)2 HttpHeaders (org.springframework.http.HttpHeaders)2 HttpMethod (org.springframework.http.HttpMethod)2 ServletServerHttpRequest (org.springframework.http.server.reactive.ServletServerHttpRequest)2 ServletServerHttpResponse (org.springframework.http.server.reactive.ServletServerHttpResponse)2