Search in sources :

Example 21 with DataBufferFactory

use of org.springframework.core.io.buffer.DataBufferFactory in project spring-integration by spring-projects.

the class WebFluxDslTests method testWebFluxFlowWithReplyPayloadToFlux.

@Test
public void testWebFluxFlowWithReplyPayloadToFlux() {
    ClientHttpConnector httpConnector = new HttpHandlerConnector((request, response) -> {
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
        DataBufferFactory bufferFactory = response.bufferFactory();
        return response.writeWith(Mono.just(bufferFactory.wrap("FOO\nBAR\n".getBytes()))).then(Mono.defer(response::setComplete));
    });
    WebClient webClient = WebClient.builder().clientConnector(httpConnector).build();
    new DirectFieldAccessor(this.webFluxWithReplyPayloadToFlux).setPropertyValue("webClient", webClient);
    QueueChannel replyChannel = new QueueChannel();
    Message<String> testMessage = MessageBuilder.withPayload("test").setReplyChannel(replyChannel).build();
    this.webFluxFlowWithReplyPayloadToFluxInput.send(testMessage);
    Message<?> receive = replyChannel.receive(10_000);
    assertNotNull(receive);
    assertThat(receive.getPayload(), instanceOf(Flux.class));
    @SuppressWarnings("unchecked") Flux<String> response = (Flux<String>) receive.getPayload();
    StepVerifier.create(response).expectNext("FOO", "BAR").verifyComplete();
}
Also used : ClientHttpConnector(org.springframework.http.client.reactive.ClientHttpConnector) QueueChannel(org.springframework.integration.channel.QueueChannel) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) EnableWebFlux(org.springframework.web.reactive.config.EnableWebFlux) Flux(reactor.core.publisher.Flux) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) WebClient(org.springframework.web.reactive.function.client.WebClient) HttpHandlerConnector(org.springframework.test.web.reactive.server.HttpHandlerConnector) Test(org.junit.Test)

Example 22 with DataBufferFactory

use of org.springframework.core.io.buffer.DataBufferFactory in project spring-data-mongodb by spring-projects.

the class ReactiveGridFsTemplateTests method considersSkipLimitWhenQueryingFiles.

// DATAMONGO-765
@Test
public void considersSkipLimitWhenQueryingFiles() {
    DataBufferFactory bufferFactory = new DefaultDataBufferFactory();
    DataBuffer buffer = bufferFactory.allocateBuffer(0);
    // 
    Flux.just(// 
    "a", // 
    "aa", // 
    "aaa", // 
    "b", // 
    "bb", // 
    "bbb", // 
    "c", // 
    "cc", // 
    "ccc", "d", "dd", // 
    "ddd").flatMap(// 
    fileName -> operations.store(Mono.just(buffer), fileName)).as(// 
    StepVerifier::create).expectNextCount(// 
    12).verifyComplete();
    PageRequest pageRequest = PageRequest.of(2, 3, Sort.Direction.ASC, "filename");
    // 
    operations.find(new Query().with(pageRequest)).map(// 
    GridFSFile::getFilename).as(// 
    StepVerifier::create).expectNext("c", "cc", // 
    "ccc").verifyComplete();
}
Also used : Document(org.bson.Document) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) StepVerifier(reactor.test.StepVerifier) DefaultDataBufferFactory(org.springframework.core.io.buffer.DefaultDataBufferFactory) RunWith(org.junit.runner.RunWith) ClassPathResource(org.springframework.core.io.ClassPathResource) DefaultDataBuffer(org.springframework.core.io.buffer.DefaultDataBuffer) Autowired(org.springframework.beans.factory.annotation.Autowired) BsonString(org.bson.BsonString) MongoConverter(org.springframework.data.mongodb.core.convert.MongoConverter) ByteBuffer(java.nio.ByteBuffer) Assertions(org.assertj.core.api.Assertions) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) Sort(org.springframework.data.domain.Sort) SpringRunner(org.springframework.test.context.junit4.SpringRunner) Before(org.junit.Before) Resource(org.springframework.core.io.Resource) StreamUtils(org.springframework.util.StreamUtils) GridFSFile(com.mongodb.client.gridfs.model.GridFSFile) BsonObjectId(org.bson.BsonObjectId) PageRequest(org.springframework.data.domain.PageRequest) Mono(reactor.core.publisher.Mono) IOException(java.io.IOException) Test(org.junit.Test) GridFsCriteria(org.springframework.data.mongodb.gridfs.GridFsCriteria) DataBuffer(org.springframework.core.io.buffer.DataBuffer) InputStreamReader(java.io.InputStreamReader) Criteria(org.springframework.data.mongodb.core.query.Criteria) Query(org.springframework.data.mongodb.core.query.Query) Flux(reactor.core.publisher.Flux) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) ContextConfiguration(org.springframework.test.context.ContextConfiguration) ObjectId(org.bson.types.ObjectId) ReactiveMongoDatabaseFactory(org.springframework.data.mongodb.ReactiveMongoDatabaseFactory) HexUtils(com.mongodb.internal.HexUtils) FileCopyUtils(org.springframework.util.FileCopyUtils) SimpleMongoClientDatabaseFactory(org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory) PageRequest(org.springframework.data.domain.PageRequest) Query(org.springframework.data.mongodb.core.query.Query) DefaultDataBufferFactory(org.springframework.core.io.buffer.DefaultDataBufferFactory) StepVerifier(reactor.test.StepVerifier) DefaultDataBufferFactory(org.springframework.core.io.buffer.DefaultDataBufferFactory) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) DefaultDataBuffer(org.springframework.core.io.buffer.DefaultDataBuffer) DataBuffer(org.springframework.core.io.buffer.DataBuffer) Test(org.junit.Test)

Example 23 with DataBufferFactory

use of org.springframework.core.io.buffer.DataBufferFactory in project spring-framework by spring-projects.

the class ScriptUtils method executeSqlScript.

/**
 * Execute the given SQL script.
 * <p>Statement separators and comments will be removed before executing
 * individual statements within the supplied script.
 * <p><strong>Warning</strong>: this method does <em>not</em> release the
 * provided {@link Connection}.
 * @param connection the R2DBC connection to use to execute the script; already
 * configured and ready to use
 * @param resource the resource (potentially associated with a specific encoding)
 * to load the SQL script from
 * @param dataBufferFactory the factory to create data buffers with
 * @param continueOnError whether or not to continue without throwing an exception
 * in the event of an error
 * @param ignoreFailedDrops whether or not to continue in the event of specifically
 * an error on a {@code DROP} statement
 * @param commentPrefixes the prefixes that identify single-line comments in the
 * SQL script (typically "--")
 * @param separator the script statement separator; defaults to
 * {@value #DEFAULT_STATEMENT_SEPARATOR} if not specified and falls back to
 * {@value #FALLBACK_STATEMENT_SEPARATOR} as a last resort; may be set to
 * {@value #EOF_STATEMENT_SEPARATOR} to signal that the script contains a
 * single statement without a separator
 * @param blockCommentStartDelimiter the <em>start</em> block comment delimiter
 * @param blockCommentEndDelimiter the <em>end</em> block comment delimiter
 * @throws ScriptException if an error occurred while executing the SQL script
 * @see #DEFAULT_STATEMENT_SEPARATOR
 * @see #FALLBACK_STATEMENT_SEPARATOR
 * @see #EOF_STATEMENT_SEPARATOR
 * @see org.springframework.r2dbc.connection.ConnectionFactoryUtils#getConnection
 * @see org.springframework.r2dbc.connection.ConnectionFactoryUtils#releaseConnection
 */
public static Mono<Void> executeSqlScript(Connection connection, EncodedResource resource, DataBufferFactory dataBufferFactory, boolean continueOnError, boolean ignoreFailedDrops, String[] commentPrefixes, @Nullable String separator, String blockCommentStartDelimiter, String blockCommentEndDelimiter) throws ScriptException {
    if (logger.isDebugEnabled()) {
        logger.debug("Executing SQL script from " + resource);
    }
    long startTime = System.currentTimeMillis();
    Mono<String> inputScript = readScript(resource, dataBufferFactory, separator).onErrorMap(IOException.class, ex -> new CannotReadScriptException(resource, ex));
    AtomicInteger statementNumber = new AtomicInteger();
    Flux<Void> executeScript = inputScript.flatMapIterable(script -> {
        String separatorToUse = separator;
        if (separatorToUse == null) {
            separatorToUse = DEFAULT_STATEMENT_SEPARATOR;
        }
        if (!EOF_STATEMENT_SEPARATOR.equals(separatorToUse) && !containsStatementSeparator(resource, script, separatorToUse, commentPrefixes, blockCommentStartDelimiter, blockCommentEndDelimiter)) {
            separatorToUse = FALLBACK_STATEMENT_SEPARATOR;
        }
        return splitSqlScript(resource, script, separatorToUse, commentPrefixes, blockCommentStartDelimiter, blockCommentEndDelimiter);
    }).concatMap(statement -> {
        statementNumber.incrementAndGet();
        return runStatement(statement, connection, resource, continueOnError, ignoreFailedDrops, statementNumber);
    });
    if (logger.isDebugEnabled()) {
        executeScript = executeScript.doOnComplete(() -> {
            long elapsedTime = System.currentTimeMillis() - startTime;
            logger.debug("Executed SQL script from " + resource + " in " + elapsedTime + " ms.");
        });
    }
    return executeScript.onErrorMap(ex -> !(ex instanceof ScriptException), ex -> new UncategorizedScriptException("Failed to execute database script from resource [" + resource + "]", ex)).then();
}
Also used : DefaultDataBufferFactory(org.springframework.core.io.buffer.DefaultDataBufferFactory) Publisher(org.reactivestreams.Publisher) IOException(java.io.IOException) LineNumberReader(java.io.LineNumberReader) Mono(reactor.core.publisher.Mono) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) Connection(io.r2dbc.spi.Connection) Flux(reactor.core.publisher.Flux) List(java.util.List) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) EncodedResource(org.springframework.core.io.support.EncodedResource) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) Result(io.r2dbc.spi.Result) Log(org.apache.commons.logging.Log) Nullable(org.springframework.lang.Nullable) LogFactory(org.apache.commons.logging.LogFactory) InputStream(java.io.InputStream) Resource(org.springframework.core.io.Resource) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 24 with DataBufferFactory

use of org.springframework.core.io.buffer.DataBufferFactory in project spring-framework by spring-projects.

the class MultipartHttpMessageWriter method encodePart.

@SuppressWarnings("unchecked")
private <T> Flux<DataBuffer> encodePart(byte[] boundary, String name, T value, DataBufferFactory factory) {
    MultipartHttpOutputMessage message = new MultipartHttpOutputMessage(factory);
    HttpHeaders headers = message.getHeaders();
    T body;
    ResolvableType resolvableType = null;
    if (value instanceof HttpEntity) {
        HttpEntity<T> httpEntity = (HttpEntity<T>) value;
        headers.putAll(httpEntity.getHeaders());
        body = httpEntity.getBody();
        Assert.state(body != null, "MultipartHttpMessageWriter only supports HttpEntity with body");
        if (httpEntity instanceof ResolvableTypeProvider) {
            resolvableType = ((ResolvableTypeProvider) httpEntity).getResolvableType();
        }
    } else {
        body = value;
    }
    if (resolvableType == null) {
        resolvableType = ResolvableType.forClass(body.getClass());
    }
    if (!headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
        if (body instanceof Resource) {
            headers.setContentDispositionFormData(name, ((Resource) body).getFilename());
        } else if (resolvableType.resolve() == Resource.class) {
            body = (T) Mono.from((Publisher<?>) body).doOnNext(o -> headers.setContentDispositionFormData(name, ((Resource) o).getFilename()));
        } else {
            headers.setContentDispositionFormData(name, null);
        }
    }
    MediaType contentType = headers.getContentType();
    final ResolvableType finalBodyType = resolvableType;
    Optional<HttpMessageWriter<?>> writer = this.partWriters.stream().filter(partWriter -> partWriter.canWrite(finalBodyType, contentType)).findFirst();
    if (!writer.isPresent()) {
        return Flux.error(new CodecException("No suitable writer found for part: " + name));
    }
    Publisher<T> bodyPublisher = body instanceof Publisher ? (Publisher<T>) body : Mono.just(body);
    // The writer will call MultipartHttpOutputMessage#write which doesn't actually write
    // but only stores the body Flux and returns Mono.empty().
    Mono<Void> partContentReady = ((HttpMessageWriter<T>) writer.get()).write(bodyPublisher, resolvableType, contentType, message, DEFAULT_HINTS);
    // After partContentReady, we can access the part content from MultipartHttpOutputMessage
    // and use it for writing to the actual request body
    Flux<DataBuffer> partContent = partContentReady.thenMany(Flux.defer(message::getBody));
    return Flux.concat(generateBoundaryLine(boundary, factory), partContent, generateNewLine(factory));
}
Also used : CharSequenceEncoder(org.springframework.core.codec.CharSequenceEncoder) Arrays(java.util.Arrays) ResourceHttpMessageWriter(org.springframework.http.codec.ResourceHttpMessageWriter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Hints(org.springframework.core.codec.Hints) ResolvableTypeProvider(org.springframework.core.ResolvableTypeProvider) Supplier(java.util.function.Supplier) ReactiveHttpOutputMessage(org.springframework.http.ReactiveHttpOutputMessage) ArrayList(java.util.ArrayList) CodecException(org.springframework.core.codec.CodecException) LogFormatUtils(org.springframework.core.log.LogFormatUtils) EncoderHttpMessageWriter(org.springframework.http.codec.EncoderHttpMessageWriter) Map(java.util.Map) DataBufferUtils(org.springframework.core.io.buffer.DataBufferUtils) Nullable(org.springframework.lang.Nullable) ResolvableType(org.springframework.core.ResolvableType) Resource(org.springframework.core.io.Resource) HttpHeaders(org.springframework.http.HttpHeaders) FormHttpMessageWriter(org.springframework.http.codec.FormHttpMessageWriter) Publisher(org.reactivestreams.Publisher) MediaType(org.springframework.http.MediaType) PooledDataBuffer(org.springframework.core.io.buffer.PooledDataBuffer) MultiValueMap(org.springframework.util.MultiValueMap) Mono(reactor.core.publisher.Mono) DataBuffer(org.springframework.core.io.buffer.DataBuffer) Flux(reactor.core.publisher.Flux) List(java.util.List) HttpEntity(org.springframework.http.HttpEntity) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) Optional(java.util.Optional) Collections(java.util.Collections) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) Assert(org.springframework.util.Assert) HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) ResourceHttpMessageWriter(org.springframework.http.codec.ResourceHttpMessageWriter) EncoderHttpMessageWriter(org.springframework.http.codec.EncoderHttpMessageWriter) FormHttpMessageWriter(org.springframework.http.codec.FormHttpMessageWriter) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) Resource(org.springframework.core.io.Resource) Publisher(org.reactivestreams.Publisher) MediaType(org.springframework.http.MediaType) CodecException(org.springframework.core.codec.CodecException) ResolvableType(org.springframework.core.ResolvableType) ResolvableTypeProvider(org.springframework.core.ResolvableTypeProvider) PooledDataBuffer(org.springframework.core.io.buffer.PooledDataBuffer) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Example 25 with DataBufferFactory

use of org.springframework.core.io.buffer.DataBufferFactory in project spring-framework by spring-projects.

the class JettyRequestUpgradeStrategy method upgrade.

@Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, @Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory) {
    ServerHttpRequest request = exchange.getRequest();
    ServerHttpResponse response = exchange.getResponse();
    HttpServletRequest servletRequest = ServerHttpRequestDecorator.getNativeRequest(request);
    HttpServletResponse servletResponse = ServerHttpResponseDecorator.getNativeResponse(response);
    ServletContext servletContext = servletRequest.getServletContext();
    HandshakeInfo handshakeInfo = handshakeInfoFactory.get();
    DataBufferFactory factory = response.bufferFactory();
    // Trigger WebFlux preCommit actions before upgrade
    return exchange.getResponse().setComplete().then(Mono.deferContextual(contextView -> {
        JettyWebSocketHandlerAdapter adapter = new JettyWebSocketHandlerAdapter(ContextWebSocketHandler.decorate(handler, contextView), session -> new JettyWebSocketSession(session, handshakeInfo, factory));
        JettyWebSocketCreator webSocketCreator = (upgradeRequest, upgradeResponse) -> {
            if (subProtocol != null) {
                upgradeResponse.setAcceptedSubProtocol(subProtocol);
            }
            return adapter;
        };
        JettyWebSocketServerContainer container = JettyWebSocketServerContainer.getContainer(servletContext);
        try {
            container.upgrade(webSocketCreator, servletRequest, servletResponse);
        } catch (Exception ex) {
            return Mono.error(ex);
        }
        return Mono.empty();
    }));
}
Also used : JettyWebSocketHandlerAdapter(org.springframework.web.reactive.socket.adapter.JettyWebSocketHandlerAdapter) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo) RequestUpgradeStrategy(org.springframework.web.reactive.socket.server.RequestUpgradeStrategy) Mono(reactor.core.publisher.Mono) Supplier(java.util.function.Supplier) ServerWebExchange(org.springframework.web.server.ServerWebExchange) JettyWebSocketCreator(org.eclipse.jetty.websocket.server.JettyWebSocketCreator) JettyWebSocketServerContainer(org.eclipse.jetty.websocket.server.JettyWebSocketServerContainer) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) ServerHttpRequestDecorator(org.springframework.http.server.reactive.ServerHttpRequestDecorator) ServerHttpResponseDecorator(org.springframework.http.server.reactive.ServerHttpResponseDecorator) Nullable(org.springframework.lang.Nullable) WebSocketHandler(org.springframework.web.reactive.socket.WebSocketHandler) ContextWebSocketHandler(org.springframework.web.reactive.socket.adapter.ContextWebSocketHandler) ServletContext(jakarta.servlet.ServletContext) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) JettyWebSocketSession(org.springframework.web.reactive.socket.adapter.JettyWebSocketSession) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) JettyWebSocketSession(org.springframework.web.reactive.socket.adapter.JettyWebSocketSession) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) JettyWebSocketCreator(org.eclipse.jetty.websocket.server.JettyWebSocketCreator) ServerHttpResponse(org.springframework.http.server.reactive.ServerHttpResponse) JettyWebSocketHandlerAdapter(org.springframework.web.reactive.socket.adapter.JettyWebSocketHandlerAdapter) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) JettyWebSocketServerContainer(org.eclipse.jetty.websocket.server.JettyWebSocketServerContainer) ServletContext(jakarta.servlet.ServletContext) DataBufferFactory(org.springframework.core.io.buffer.DataBufferFactory) HandshakeInfo(org.springframework.web.reactive.socket.HandshakeInfo)

Aggregations

DataBufferFactory (org.springframework.core.io.buffer.DataBufferFactory)28 DataBuffer (org.springframework.core.io.buffer.DataBuffer)14 Mono (reactor.core.publisher.Mono)12 Flux (reactor.core.publisher.Flux)11 List (java.util.List)9 Publisher (org.reactivestreams.Publisher)8 Nullable (org.springframework.lang.Nullable)8 IOException (java.io.IOException)7 MediaType (org.springframework.http.MediaType)7 Assert (org.springframework.util.Assert)7 HandshakeInfo (org.springframework.web.reactive.socket.HandshakeInfo)7 Collections (java.util.Collections)6 Resource (org.springframework.core.io.Resource)6 ServerHttpRequest (org.springframework.http.server.reactive.ServerHttpRequest)6 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5 Supplier (java.util.function.Supplier)5 ResolvableType (org.springframework.core.ResolvableType)5 DataBufferUtils (org.springframework.core.io.buffer.DataBufferUtils)5 Test (org.junit.Test)4