Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.baeldung.spring.convert.databuffertomono;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public class DataBufferConverter {
public Mono<byte[]> toByteArray(Flux<DataBuffer> data) {
return DataBufferUtils
// Here, we'll join all DataBuffers in the Flux into a single Mono<DataBuffer>.
.join(data)
.flatMap(dataBuffer -> {
try {
// Next, extract the byte[] from the aggregated DataBuffer manually.
byte[] bytes = new byte[dataBuffer.readableByteCount()];
dataBuffer.read(bytes);
return Mono.just(bytes);
} finally {
// Ensure the final aggregated DataBuffer is released.
DataBufferUtils.release(dataBuffer);
}
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.baeldung.spring.convert.databuffertomono;

import org.junit.jupiter.api.Test;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import reactor.core.publisher.Flux;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;

public class DataBufferConverterTest {

private final DataBufferConverter converter = new DataBufferConverter();
private final DefaultDataBufferFactory factory = new DefaultDataBufferFactory();
private final String TEST_CONTENT = "This is a long test string.";

@Test
void givenFluxOfDataBuffers_whenConvertedToByteArray_thenContentMatches() {
// Setup: First, we'll manually create two DataBuffer chunks for the input Flux
byte[] part1 = "This is a ".getBytes();
byte[] part2 = "long test string.".getBytes();

DataBuffer buffer1 = factory.allocateBuffer(part1.length);
buffer1.write(part1);

DataBuffer buffer2 = factory.allocateBuffer(part2.length);
buffer2.write(part2);

Flux<DataBuffer> sourceFlux = Flux.just(buffer1, buffer2);

// Act & Assert: Here we perform conversion and block for direct assertion
byte[] resultBytes = converter.toByteArray(sourceFlux).block();

byte[] expectedBytes = TEST_CONTENT.getBytes();
assertArrayEquals(expectedBytes, resultBytes, "The reconstructed byte array should match original");
}
}