Java Code Examples for reactor.core.publisher.Flux#concat()

The following examples show how to use reactor.core.publisher.Flux#concat() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: R021_FluxSubscribing.java    From reactor-workshop with GNU General Public License v3.0 6 votes vote down vote up
/**
 * TODO create a {@link Flux} that <b>fails</b> after emitting few values
 * Hint: {@link Flux#concat(Publisher[])} with failing {@link Flux} as second argument
 */
@Test
public void fluxThatFailsAfterEmitting() throws Exception {
	//given

	//when
	final Flux<Integer> work = Flux.concat(
			null,
			null
	);

	//then
	work.subscribe(
			onNext::add,
			error::set,
			() -> completed.set(true)
	);

	assertThat(onNext).containsExactly(1, 2, 3);
	assertThat(error.get())
			.isInstanceOf(IOException.class)
			.hasMessage("Simulated");
	assertThat(completed).isFalse();
}
 
Example 2
Source File: DataBufferUtilsTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void splitAcrossBuffer() {
	Flux<DataBuffer> source = Flux.concat(
			deferStringBuffer("foo-"),
			deferStringBuffer("-bar-"),
			deferStringBuffer("-baz"));

	byte[] delimiter = "--".getBytes(StandardCharsets.UTF_8);

	Flux<DataBuffer> result = DataBufferUtils.split(source, delimiter);

	StepVerifier.create(result)
			.consumeNextWith(stringConsumer("foo"))
			.consumeNextWith(stringConsumer("bar"))
			.consumeNextWith(stringConsumer("baz"))
			.verifyComplete();
}
 
Example 3
Source File: ResourceDecoderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void decodeToMono() throws Exception {
	Flux<DataBuffer> input = Flux.concat(
			dataBuffer(this.fooBytes),
			dataBuffer(this.barBytes));

	testDecodeToMonoAll(input, Resource.class, step -> step
			.consumeNextWith(resource -> {
				try {
					byte[] bytes = StreamUtils.copyToByteArray(resource.getInputStream());
					assertEquals("foobar", new String(bytes));
				}
				catch (IOException e) {
					fail(e.getMessage());
				}
			})
			.expectComplete()
			.verify());
}
 
Example 4
Source File: R043_Zip.java    From reactor-workshop with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void errorBreaksZip() throws Exception {
	//given
	final Flux<Integer> nums = Flux.just(1, 2, 3);
	final Flux<String> strs = Flux.concat(
			Flux.just("a", "b"),
			Flux.error(new RuntimeException("Opps"))
	);

	//when
	final Flux<Tuple2<Integer, String>> pairs = nums.zipWith(strs);

	//then
	pairs
			.as(StepVerifier::create)
			.expectNext(Tuples.of(1, "a"))
			.expectNext(Tuples.of(2, "b"))
			.verifyErrorMatches(e -> e.getMessage().equals("Opps"));
}
 
Example 5
Source File: Jackson2JsonDecoderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Test
public void decode() {
	Flux<DataBuffer> input = Flux.concat(
			stringBuffer("[{\"bar\":\"b1\",\"foo\":\"f1\"},"),
			stringBuffer("{\"bar\":\"b2\",\"foo\":\"f2\"}]"));

	testDecodeAll(input, Pojo.class, step -> step
			.expectNext(pojo1)
			.expectNext(pojo2)
			.verifyComplete());
}
 
Example 6
Source File: XmlEventDecoderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void decodeErrorAalto() {
	Flux<DataBuffer> source = Flux.concat(
			stringBuffer("<pojo>"),
			Flux.error(new RuntimeException()));

	Flux<XMLEvent> events =
			this.decoder.decode(source, null, null, Collections.emptyMap());

	StepVerifier.create(events)
			.consumeNextWith(e -> assertTrue(e.isStartDocument()))
			.consumeNextWith(e -> assertStartElement(e, "pojo"))
			.expectError(RuntimeException.class)
			.verify();
}
 
Example 7
Source File: R2dbcServiceInstanceMetricsRepository.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
public Flux<Tuple2<String, Long>> totalVelocity() {
	final LocalDate now = LocalDate.now();
	return
		Flux.concat(
			countByDateRange(now.minusDays(1), now).map(r -> Tuples.of("in-last-day", r)),
			countByDateRange(now.minusDays(2), now.minusDays(1)).map(r -> Tuples.of("between-one-day-and-two-days", r)),
			countByDateRange(now.minusWeeks(1), now.minusDays(2)).map(r -> Tuples.of("between-two-days-and-one-week", r)),
			countByDateRange(now.minusWeeks(2), now.minusWeeks(1)).map(r -> Tuples.of("between-one-week-and-two-weeks", r)),
			countByDateRange(now.minusMonths(1), now.minusWeeks(2)).map(r -> Tuples.of("between-two-weeks-and-one-month", r)),
			countByDateRange(now.minusMonths(3), now.minusMonths(1)).map(r -> Tuples.of("between-one-month-and-three-months", r)),
			countByDateRange(now.minusMonths(6), now.minusMonths(3)).map(r -> Tuples.of("between-three-months-and-six-months", r)),
			countByDateRange(now.minusYears(1), now.minusMonths(6)).map(r -> Tuples.of("between-six-months-and-one-year", r)),
			countStagnant(now.minusYears(1)).map(r -> Tuples.of("beyond-one-year", r)));
}
 
Example 8
Source File: DataBufferDecoderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void decodeToMono() throws Exception {
	Flux<DataBuffer> input = Flux.concat(
			dataBuffer(this.fooBytes),
			dataBuffer(this.barBytes));

	byte[] expected = new byte[this.fooBytes.length + this.barBytes.length];
	System.arraycopy(this.fooBytes, 0, expected, 0, this.fooBytes.length);
	System.arraycopy(this.barBytes, 0, expected, this.fooBytes.length, this.barBytes.length);

	testDecodeToMonoAll(input, DataBuffer.class, step -> step
			.consumeNextWith(expectDataBuffer(expected))
			.verifyComplete());
}
 
Example 9
Source File: AbstractDecoderTestCase.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Test a {@link Decoder#decode decode} scenario where the input stream contains an error.
 * This test method will feed the first element of the {@code input} stream to the decoder,
 * followed by an {@link InputException}.
 * The result is expected to contain one "normal" element, followed by the error.
 *
 * @param input the input to be provided to the decoder
 * @param outputType the desired output type
 * @param mimeType the mime type to use for decoding. May be {@code null}.
 * @param hints the hints used for decoding. May be {@code null}.
 * @see InputException
 */
protected void testDecodeError(Publisher<DataBuffer> input, ResolvableType outputType,
		@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

	input = Flux.concat(
			Flux.from(input).take(1),
			Flux.error(new InputException()));

	Flux<?> result = this.decoder.decode(input, outputType, mimeType, hints);

	StepVerifier.create(result)
			.expectNextCount(1)
			.expectError(InputException.class)
			.verify();
}
 
Example 10
Source File: DataBufferUtilsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void skipUntilByteCountCancelled() {
	Flux<DataBuffer> source = Flux.concat(
			deferStringBuffer("foo"),
			deferStringBuffer("bar")
	);
	Flux<DataBuffer> result = DataBufferUtils.skipUntilByteCount(source, 5L);

	StepVerifier.create(result)
			.consumeNextWith(stringConsumer("r"))
			.thenCancel()
			.verify(Duration.ofSeconds(5));
}
 
Example 11
Source File: AbstractDecoderTestCase.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Test a {@link Decoder#decodeToMono decode} scenario where the input stream contains an error.
 * This test method will feed the first element of the {@code input} stream to the decoder,
 * followed by an {@link InputException}.
 * The result is expected to contain the error.
 *
 * @param input the input to be provided to the decoder
 * @param outputType the desired output type
 * @param mimeType the mime type to use for decoding. May be {@code null}.
 * @param hints the hints used for decoding. May be {@code null}.
 * @see InputException
 */
protected void testDecodeToMonoError(Publisher<DataBuffer> input, ResolvableType outputType,
		@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

	input = Flux.concat(
			Flux.from(input).take(1),
			Flux.error(new InputException()));

	Mono<?> result = this.decoder.decodeToMono(input, outputType, mimeType, hints);

	StepVerifier.create(result)
			.expectError(InputException.class)
			.verify();
}
 
Example 12
Source File: DataBufferUtilsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void takeUntilByteCountCanceled() {
	Flux<DataBuffer> source = Flux.concat(
			deferStringBuffer("foo"),
			deferStringBuffer("bar")
	);
	Flux<DataBuffer> result = DataBufferUtils.takeUntilByteCount(
			source, 5L);

	StepVerifier.create(result)
			.consumeNextWith(stringConsumer("foo"))
			.thenCancel()
			.verify(Duration.ofSeconds(5));
}
 
Example 13
Source File: DataBufferDecoderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public void decodeToMono() throws Exception {
	Flux<DataBuffer> input = Flux.concat(
			dataBuffer(this.fooBytes),
			dataBuffer(this.barBytes));

	byte[] expected = new byte[this.fooBytes.length + this.barBytes.length];
	System.arraycopy(this.fooBytes, 0, expected, 0, this.fooBytes.length);
	System.arraycopy(this.barBytes, 0, expected, this.fooBytes.length, this.barBytes.length);

	testDecodeToMonoAll(input, DataBuffer.class, step -> step
			.consumeNextWith(expectDataBuffer(expected))
			.verifyComplete());
}
 
Example 14
Source File: DataChunker.java    From james-project with Apache License 2.0 5 votes vote down vote up
public Flux<ByteBuffer> chunk(byte[] data, int chunkSize) {
    Preconditions.checkNotNull(data);
    Preconditions.checkArgument(chunkSize > 0, CHUNK_SIZE_MUST_BE_STRICTLY_POSITIVE);

    int size = data.length;
    int fullChunkCount = size / chunkSize;

    return Flux.concat(
        Flux.range(0, fullChunkCount)
            .map(i -> ByteBuffer.wrap(data, i * chunkSize, chunkSize)),
        lastChunk(data, chunkSize * fullChunkCount, fullChunkCount));
}
 
Example 15
Source File: R2dbcAppMetricsRepository.java    From cf-butler with Apache License 2.0 5 votes vote down vote up
public Flux<Tuple2<String, Long>> totalVelocity() {
	final LocalDate now = LocalDate.now();
	return
		Flux.concat(
			countByDateRange(now.minusDays(1), now).map(r -> Tuples.of("in-last-day", r)),
			countByDateRange(now.minusDays(2), now.minusDays(1)).map(r -> Tuples.of("between-one-day-and-two-days", r)),
			countByDateRange(now.minusWeeks(1), now.minusDays(2)).map(r -> Tuples.of("between-two-days-and-one-week", r)),
			countByDateRange(now.minusWeeks(2), now.minusWeeks(1)).map(r -> Tuples.of("between-one-week-and-two-weeks", r)),
			countByDateRange(now.minusMonths(1), now.minusWeeks(2)).map(r -> Tuples.of("between-two-weeks-and-one-month", r)),
			countByDateRange(now.minusMonths(3), now.minusMonths(1)).map(r -> Tuples.of("between-one-month-and-three-months", r)),
			countByDateRange(now.minusMonths(6), now.minusMonths(3)).map(r -> Tuples.of("between-three-months-and-six-months", r)),
			countByDateRange(now.minusYears(1), now.minusMonths(6)).map(r -> Tuples.of("between-six-months-and-one-year", r)),
			countStagnant(now.minusYears(1)).map(r -> Tuples.of("beyond-one-year", r)));
}
 
Example 16
Source File: ByteBufferDecoderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Test
public void decode() {
	Flux<DataBuffer> input = Flux.concat(
			dataBuffer(this.fooBytes),
			dataBuffer(this.barBytes));

	testDecodeAll(input, ByteBuffer.class, step -> step
			.consumeNextWith(expectByteBuffer(ByteBuffer.wrap(this.fooBytes)))
			.consumeNextWith(expectByteBuffer(ByteBuffer.wrap(this.barBytes)))
			.verifyComplete());


}
 
Example 17
Source File: DomainBuilder.java    From hedera-mirror-node with Apache License 2.0 5 votes vote down vote up
public Flux<TopicMessage> topicMessages(long count, Instant startTime) {
    List<Publisher<TopicMessage>> publishers = new ArrayList<>();
    for (int i = 0; i < count; ++i) {
        Instant consensusTimestamp = startTime.plusNanos(i);
        publishers.add(topicMessage(t -> t.consensusTimestamp(consensusTimestamp)));
    }
    return Flux.concat(publishers);
}
 
Example 18
Source File: StringDecoderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void testDecodeError(Publisher<DataBuffer> input, ResolvableType outputType,
		@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

	input = Flux.concat(
			Flux.from(input).take(1),
			Flux.error(new InputException()));

	Flux<String> result = this.decoder.decode(input, outputType, mimeType, hints);

	StepVerifier.create(result)
			.expectError(InputException.class)
			.verify();
}
 
Example 19
Source File: ReactiveRepositoryIT.java    From sdn-rx with Apache License 2.0 4 votes vote down vote up
@Test
void updateWithAssignedId(@Autowired ReactiveThingRepository repository) {

	Flux<ThingWithAssignedId> operationUnderTest = Flux.concat(
		// Without prior selection
		Mono.fromSupplier(() -> {
			ThingWithAssignedId thing = new ThingWithAssignedId("id07");
			thing.setName("An updated thing");
			return thing;
		}).flatMap(repository::save),

		// With prior selection
		repository.findById("id15")
			.flatMap(thing -> {
				thing.setName("Another updated thing");
				return repository.save(thing);
			})
	);

	TransactionalOperator transactionalOperator = TransactionalOperator.create(getTransactionManager());
	transactionalOperator
		.execute(t -> operationUnderTest)
		.as(StepVerifier::create)
		.expectNextCount(2L)
		.verifyComplete();

	Flux
		.usingWhen(
			Mono.fromSupplier(() -> createRxSession()),
			s -> {
				Value parameters = parameters("ids", Arrays.asList("id07", "id15"));
				return s.run("MATCH (n:Thing) WHERE n.theId IN ($ids) RETURN n.name as name ORDER BY n.name ASC",
					parameters).records();
			},
			RxSession::close
		)
		.map(r -> r.get("name").asString())
		.as(StepVerifier::create)
		.expectNext("An updated thing", "Another updated thing")
		.verifyComplete();

	repository.count().as(StepVerifier::create).expectNext(21L).verifyComplete();
}
 
Example 20
Source File: MultipartHttpMessageWriter.java    From java-technology-stack with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> Flux<DataBuffer> encodePart(byte[] boundary, String name, T value) {
	MultipartHttpOutputMessage outputMessage = new MultipartHttpOutputMessage(this.bufferFactory, getCharset());
	HttpHeaders outputHeaders = outputMessage.getHeaders();

	T body;
	ResolvableType resolvableType = null;
	if (value instanceof HttpEntity) {
		HttpEntity<T> httpEntity = (HttpEntity<T>) value;
		outputHeaders.putAll(httpEntity.getHeaders());
		body = httpEntity.getBody();
		Assert.state(body != null, "MultipartHttpMessageWriter only supports HttpEntity with body");

		if (httpEntity instanceof MultipartBodyBuilder.PublisherEntity<?, ?>) {
			MultipartBodyBuilder.PublisherEntity<?, ?> publisherEntity =
					(MultipartBodyBuilder.PublisherEntity<?, ?>) httpEntity;
			resolvableType = publisherEntity.getResolvableType();
		}
	}
	else {
		body = value;
	}
	if (resolvableType == null) {
		resolvableType = ResolvableType.forClass(body.getClass());
	}

	if (!outputHeaders.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		if (body instanceof Resource) {
			outputHeaders.setContentDispositionFormData(name, ((Resource) body).getFilename());
		}
		else if (resolvableType.resolve() == Resource.class) {
			body = (T) Mono.from((Publisher<?>) body).doOnNext(o -> outputHeaders
					.setContentDispositionFormData(name, ((Resource) o).getFilename()));
		}
		else {
			outputHeaders.setContentDispositionFormData(name, null);
		}
	}

	MediaType contentType = outputHeaders.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, outputMessage, 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(outputMessage::getBody));

	return Flux.concat(Mono.just(generateBoundaryLine(boundary)), partContent, Mono.just(generateNewLine()));
}