reactor.core.publisher.Signal Java Examples

The following examples show how to use reactor.core.publisher.Signal. 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: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Override
public void onNext(T t) {
	if (establishedFusionMode == Fuseable.ASYNC) {
		serializeDrainAndSubscriptionEvent();
	}
	else {
		produced++;
		unasserted++;
		if (currentCollector != null) {
			currentCollector.add(t);
		}
		Signal<T> signal = Signal.next(t);
		if (!checkRequestOverflow(signal)) {
			onExpectation(signal);
		}
	}
}
 
Example #2
Source File: ChannelSendOperatorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void errorAfterMultipleItems() throws Exception {
	IllegalStateException error = new IllegalStateException("boo");
	Flux<String> publisher = Flux.generate(() -> 0, (idx , subscriber) -> {
		int i = ++idx;
		subscriber.next(String.valueOf(i));
		if (i == 3) {
			subscriber.error(error);
		}
		return i;
	});
	Mono<Void> completion = publisher.as(this::sendOperator);
	Signal<Void> signal = completion.materialize().block();

	assertNotNull(signal);
	assertSame("Unexpected signal: " + signal, error, signal.getThrowable());

	assertEquals(3, this.writer.items.size());
	assertEquals("1", this.writer.items.get(0));
	assertEquals("2", this.writer.items.get(1));
	assertEquals("3", this.writer.items.get(2));
	assertSame(error, this.writer.error);
}
 
Example #3
Source File: FluxTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoOnEachSignal() {
	List<Signal<Integer>> signals = new ArrayList<>(4);
	List<Integer> values = new ArrayList<>(2);
	Flux<Integer> flux = Flux.just(1, 2)
	                         .doOnEach(signals::add)
	                         .doOnEach(s -> {
	                         	if (s.isOnNext())
	                         		values.add(s.get());
	                         });
	StepVerifier.create(flux)
	            .expectSubscription()
	            .expectNext(1, 2)
	            .expectComplete()
	            .verify();

	assertThat(signals.size(), is(3));
	assertThat("onNext signal are not reused", signals.get(0).get(), is(2));
	assertThat("onNext signal isn't last value", signals.get(1).get(), is(2));
	assertTrue("onComplete expected", signals.get(2).isOnComplete());
	assertThat("1st onNext value unexpected", values.get(0), is(1));
	assertThat("2nd onNext value unexpected", values.get(1), is(2));
}
 
Example #4
Source File: CloudFoundryAppDeployer.java    From spring-cloud-deployer-cloudfoundry with Apache License 2.0 6 votes vote down vote up
private Mono<ApplicationDetail> requestGetApplication(String id) {
	return CacheMono
		.lookup(k -> Mono.defer(() -> {
			ApplicationDetail ifPresent = cache.getIfPresent(id);
			logger.debug("Cache get {}", ifPresent);
			return Mono.justOrEmpty(ifPresent).map(Signal::next);
		}), id)
		.onCacheMissResume(Mono.defer(() -> {
			logger.debug("Cache miss {}", id);
			return getApplicationDetail(id);
		}))
		.andWriteWith((k, sig) -> Mono.fromRunnable(() -> {
			ApplicationDetail ap = sig.get();
			if (ap != null) {
				logger.debug("Cache put {} {}", k, ap);
				cache.put(k, ap);
			}
		}));
}
 
Example #5
Source File: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
/** Returns true if the requested amount was overflown by the given signal */
final boolean checkRequestOverflow(Signal<T> s) {
	long r = requested;
	if (!s.isOnNext()
			|| r < 0 || r == Long.MAX_VALUE //was Long.MAX from beginning or switched to unbounded
			|| (establishedFusionMode == Fuseable.ASYNC && r != 0L)
			|| r >= produced) {
		return false;
	}
	else {
		//not really an expectation failure so customize the message
		setFailurePrefix("request overflow (", s,
				"expected production of at most %s; produced: %s; request overflown by signal: %s", r, produced, s);
		return true;
	}
}
 
Example #6
Source File: ChannelSendOperatorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void errorAfterMultipleItems() throws Exception {
	IllegalStateException error = new IllegalStateException("boo");
	Flux<String> publisher = Flux.generate(() -> 0, (idx , subscriber) -> {
		int i = ++idx;
		subscriber.next(String.valueOf(i));
		if (i == 3) {
			subscriber.error(error);
		}
		return i;
	});
	Mono<Void> completion = publisher.as(this::sendOperator);
	Signal<Void> signal = completion.materialize().block();

	assertNotNull(signal);
	assertSame("Unexpected signal: " + signal, error, signal.getThrowable());

	assertEquals(3, this.writer.items.size());
	assertEquals("1", this.writer.items.get(0));
	assertEquals("2", this.writer.items.get(1));
	assertEquals("3", this.writer.items.get(2));
	assertSame(error, this.writer.error);
}
 
Example #7
Source File: ValueFormattersTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void convertVarargsSignalNotExtractedIfConverterMatches() {
	Extractor<Signal> extractor = ValueFormatters.signalExtractor();
	ToStringConverter converter = ValueFormatters.forClass(Object.class, o -> o.getClass().getSimpleName() + "=>" + o);
	Signal<Obscure> target = Signal.next(Obscure.OB1);

	Object[] converted = ValueFormatters.convertVarArgs(converter, Collections.singleton(extractor), target);

	assertThat(converted)
			.hasSize(1)
			.allSatisfy(o -> assertThat(o)
					.isInstanceOf(String.class)
					.isNotEqualTo(target.toString())
					.isNotEqualTo("onNext(foo)")
					.isEqualTo("ImmutableSignal=>onNext(OB1)")
			);
}
 
Example #8
Source File: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
boolean onSignal(Signal<T> actualSignal) {
	SignalEvent<T> signalEvent = (SignalEvent<T>) this.script.poll();
	Optional<AssertionError> error = signalEvent.test(actualSignal);
	if (error.isPresent()) {
		Exceptions.addThrowable(ERRORS, this, error.get());
		// #55 ensure the onError is added as a suppressed to the AssertionError
		if(actualSignal.isOnError()) {
			error.get().addSuppressed(actualSignal.getThrowable());
		}
		maybeCancel(actualSignal);
		this.completeLatch.countDown();
		return true;
	}
	if (actualSignal.isOnNext()) {
		unasserted--;
	}
	return false;
}
 
Example #9
Source File: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
Optional<AssertionError> test(Signal<T> signal, Iterator<? extends T> iterator) {
	if (signal.isOnNext()) {
		if (!iterator.hasNext()) {
			return Optional.empty();
		}
		T d2 = iterator.next();
		if (!Objects.equals(signal.get(), d2)) {
			return messageFormatter.failOptional(this, "expected : onNext(%s); actual: %s; iterable: %s",
					d2,
					signal.get(),
					iterable);
		}
		return iterator.hasNext() ? EXPECT_MORE : Optional.empty();

	}
	if (iterator.hasNext() || signal.isOnError()) {
		return messageFormatter.failOptional(this, "expected next value: %s; actual signal: %s; iterable: %s",
				iterator.hasNext() ? iterator.next() : "none",
				signal, iterable);
	}
	return Optional.empty();
}
 
Example #10
Source File: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
boolean consumeWhile(Signal<T> actualSignal, SignalConsumeWhileEvent<T> whileEvent) {
	if (actualSignal.isOnNext()) {
		if (whileEvent.test(actualSignal.get())) {
			//the value matches, gobble it up
			unasserted--;
			if (this.logger != null) {
				logger.debug("{} consumed {}", whileEvent.getDescription(), actualSignal);
			}
			return true;
		}
	}
	if (this.logger != null) {
		logger.debug("{} stopped at {}", whileEvent.getDescription(), actualSignal);
	}
	//stop evaluating the predicate
	this.script.poll();
	return false;
}
 
Example #11
Source File: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
final boolean onSignalCount(Signal<T> actualSignal, SignalCountEvent<T> event) {
	if (unasserted >= event.count) {
		this.script.poll();
		unasserted -= event.count;
	}
	else {
		if (event.count != 0) {
			Optional<AssertionError> error =
					this.checkCountMismatch(event, actualSignal);

			if (error.isPresent()) {
				Exceptions.addThrowable(ERRORS, this, error.get());
				if(actualSignal.isOnError()) {
					// #55 ensure the onError is added as a suppressed to the AssertionError
					error.get().addSuppressed(actualSignal.getThrowable());
				}
				maybeCancel(actualSignal);
				this.completeLatch.countDown();
			}
		}
		return true;
	}
	return false;
}
 
Example #12
Source File: ChannelSendOperatorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void completionBeforeFirstItem() throws Exception {
	Mono<Void> completion = Flux.<String>empty().as(this::sendOperator);
	Signal<Void> signal = completion.materialize().block();

	assertNotNull(signal);
	assertTrue("Unexpected signal: " + signal, signal.isOnComplete());

	assertEquals(0, this.writer.items.size());
	assertTrue(this.writer.completed);
}
 
Example #13
Source File: FluxTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoOnEachSignalWithError() {
	List<Signal<Integer>> signals = new ArrayList<>(4);
	Flux<Integer> flux = Flux.<Integer>error(new IllegalArgumentException("foo"))
	                         .doOnEach(signals::add);
	StepVerifier.create(flux)
	            .expectSubscription()
	            .expectErrorMessage("foo")
	            .verify();

	assertThat(signals.size(), is(1));
	assertTrue("onError expected", signals.get(0).isOnError());
	assertThat("plain exception expected", signals.get(0).getThrowable().getMessage(),
			is("foo"));
}
 
Example #14
Source File: MonoTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoOnEachSignalWithError() {
	List<Signal<Integer>> signals = new ArrayList<>(4);
	Mono<Integer> mono = Mono.<Integer>error(new IllegalArgumentException("foo"))
			.doOnEach(signals::add);
	StepVerifier.create(mono)
	            .expectSubscription()
	            .expectErrorMessage("foo")
	            .verify();

	assertThat(signals.size(), is(1));
	assertTrue("onError expected", signals.get(0).isOnError());
	assertThat("plain exception expected", signals.get(0).getThrowable().getMessage(),
			is("foo"));
}
 
Example #15
Source File: MonoTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoOnEachEmpty() {
	List<Signal<Integer>> signals = new ArrayList<>(4);
	Mono<Integer> mono = Mono.<Integer>empty()
	                         .doOnEach(signals::add);
	StepVerifier.create(mono)
	            .expectSubscription()
	            .expectComplete()
	            .verify();

	assertThat(signals.size(), is(1));
	assertTrue("onComplete expected", signals.get(0).isOnComplete());

}
 
Example #16
Source File: ValueFormattersTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void signalDoesntConvertError() {
	Extractor<Signal> extractor = ValueFormatters.signalExtractor();
	ToStringConverter converter = ValueFormatters.forClass(Obscure.class, Obscure::getAlternative);
	Signal<Number> target = Signal.error(new IllegalStateException("foo"));

	assertThat(extractor.apply(target, converter)).isEqualTo(target.toString());
}
 
Example #17
Source File: ValueFormattersTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void signalDoesntConsiderNonMatchingContent() {
	Extractor<Signal> extractor = ValueFormatters.signalExtractor();
	ToStringConverter converter = ValueFormatters.forClass(String.class, String::toUpperCase);
	Signal<Object> target = Signal.next(Obscure.OB1);

	assertThat(extractor.apply(target, converter)).isEqualTo(target.toString());
}
 
Example #18
Source File: ValueFormattersTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void signalConvertsOnNextContentMatching() {
	Extractor<Signal> extractor = ValueFormatters.signalExtractor();
	ToStringConverter converter = ValueFormatters.forClass(Obscure.class, Obscure::getAlternative);
	Signal<Obscure> target = Signal.next(Obscure.OB1);

	assertThat(extractor.apply(target, converter))
			.isNotEqualTo(target.toString())
			.isEqualTo("onNext(foo)");
}
 
Example #19
Source File: ValueFormattersTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void signalDoesntConsiderNonSignal() {
	Extractor<Signal> extractor = ValueFormatters.signalExtractor();
	ToStringConverter converter = ValueFormatters.forClass(Obscure.class, Obscure::getAlternative);
	Object target = Obscure.OB1;

	assertThat(extractor.apply(target, converter)).isEqualTo(target.toString());
}
 
Example #20
Source File: ValueFormattersTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void signalDoesntConvertErrorEvenIfThrowableClass() {
	Extractor<Signal> extractor = ValueFormatters.signalExtractor();
	ToStringConverter converter = ValueFormatters.forClass(Throwable.class, t -> t.getMessage().toUpperCase());
	Signal<Number> target = Signal.error(new IllegalStateException("foo"));

	assertThat(extractor.apply(target, converter)).isEqualTo(target.toString());
}
 
Example #21
Source File: ValueFormattersTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void signalDoesntConvertComplete() {
	Extractor<Signal> extractor = ValueFormatters.signalExtractor();
	ToStringConverter converter = ValueFormatters.forClass(Obscure.class, Obscure::getAlternative);
	Signal<Number> target = Signal.complete();

	assertThat(extractor.apply(target, converter)).isEqualTo(target.toString());
}
 
Example #22
Source File: ReactorUtils.java    From james-project with Apache License 2.0 5 votes vote down vote up
public static Consumer<Signal<?>> logOnError(Consumer<Throwable> errorLogStatement) {
    return signal -> {
        if (!signal.isOnError()) {
            return;
        }
        try {
            try (Closeable mdc = retrieveMDCBuilder(signal).build()) {
                errorLogStatement.accept(signal.getThrowable());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    };
}
 
Example #23
Source File: ReactorUtils.java    From james-project with Apache License 2.0 5 votes vote down vote up
public static Consumer<Signal<?>> log(Runnable logStatement) {
    return signal -> {
        try (Closeable mdc = retrieveMDCBuilder(signal).build()) {
            logStatement.run();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    };
}
 
Example #24
Source File: ReactorUtils.java    From james-project with Apache License 2.0 5 votes vote down vote up
private static MDCBuilder retrieveMDCBuilder(Signal<?> signal) {
    return signal.getContext().stream()
        .filter(entry -> entry.getKey() instanceof String)
        .filter(entry -> entry.getValue() instanceof MDCBuilder)
        .filter(entry -> ((String) entry.getKey()).startsWith(MDC_KEY_PREFIX))
        .map(entry -> (MDCBuilder) entry.getValue())
        .reduce(MDCBuilder.create(), MDCBuilder::addContext);
}
 
Example #25
Source File: MonoTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoOnEachSignal() {
	List<Signal<Integer>> signals = new ArrayList<>(4);
	Mono<Integer> mono = Mono.just(1)
	                         .doOnEach(signals::add);
	StepVerifier.create(mono)
	            .expectSubscription()
	            .expectNext(1)
	            .expectComplete()
	            .verify(Duration.ofSeconds(5));

	assertThat(signals.size(), is(2));
	assertThat("onNext", signals.get(0).get(), is(1));
	assertTrue("onComplete expected", signals.get(1).isOnComplete());
}
 
Example #26
Source File: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
boolean onSignalSequence(Signal<T> actualSignal,
		SignalSequenceEvent<T> sequenceEvent) {
	Iterator<? extends T> currentNextAs = this.currentNextAs;
	if (currentNextAs == null) {
		currentNextAs = sequenceEvent.iterable.iterator();
		this.currentNextAs = currentNextAs;
	}

	Optional<AssertionError> error =
			sequenceEvent.test(actualSignal, currentNextAs);

	if (error == EXPECT_MORE) {
		if (actualSignal.isOnNext()) {
			unasserted--;
		}
		return false;
	}
	if (!error.isPresent()) {
		this.currentNextAs = null;
		this.script.poll();
		if (actualSignal.isOnNext()) {
			unasserted--;
		}
	}
	else {
		Exceptions.addThrowable(ERRORS, this, error.get());
		if(actualSignal.isOnError()) {
			// #55 ensure the onError is added as a suppressed to the AssertionError
			error.get().addSuppressed(actualSignal.getThrowable());
		}
		maybeCancel(actualSignal);
		this.completeLatch.countDown();
		return true;
	}
	return false;
}
 
Example #27
Source File: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
boolean onCollect(Signal<T> actualSignal) {
	Collection<T> c;
	CollectEvent<T> collectEvent = (CollectEvent<T>) this.script.poll();
	if (collectEvent.supplier != null) {
		c = collectEvent.get();
		this.currentCollector = c;

		if (c == null) {
			setFailure(collectEvent, actualSignal, "expected collection; actual supplied is [null]");
		}
		return true;
	}
	c = this.currentCollector;

	if (c == null) {
		setFailure(collectEvent, actualSignal, "expected record collector; actual record is [null]");
		return true;
	}

	Optional<AssertionError> error = collectEvent.test(c);
	if (error.isPresent()) {
		Exceptions.addThrowable(ERRORS, this, error.get());
		maybeCancel(actualSignal);
		this.completeLatch.countDown();
		return true;
	}
	return false;
}
 
Example #28
Source File: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
final Optional<AssertionError> checkCountMismatch(SignalCountEvent<T> event, Signal<T> s) {
	long expected = event.count;
	if (!s.isOnNext()) {
		return messageFormatter.failOptional(event, "expected: count = %s; actual: counted = %s; signal: %s",
				expected,
				unasserted, s);
	}
	else {
		return Optional.empty();
	}
}
 
Example #29
Source File: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Override
public void onSubscribe(Subscription subscription) {
	Objects.requireNonNull(subscription, "onSubscribe");

	if (this.compareAndSet(null, subscription)) {
		onExpectation(Signal.subscribe(subscription));
		if (requestedFusionMode >= Fuseable.NONE) {
			startFusion(subscription);
		}
		else if (initialRequest != 0L) {
			subscription.request(initialRequest);
		}
	}
	else {
		subscription.cancel();
		if (isCancelled()) {
			setFailure(null, "an unexpected Subscription has been received: %s; actual: cancelled",
					subscription);
		}
		// subscribeOrReturn may throw an exception after calling onSubscribe.
		else if (!Operators.canAppearAfterOnSubscribe(subscription)) {
			setFailure(null, "an unexpected Subscription has been received: %s; actual: %s",
					subscription,
					this.get());
		}
	}
}
 
Example #30
Source File: DefaultStepVerifierBuilder.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Override
public void onComplete() {
	if (establishedFusionMode != Fuseable.ASYNC) {
		onExpectation(Signal.complete());
		this.completeLatch.countDown();
	}
	else {
		done = true;
		serializeDrainAndSubscriptionEvent();
	}
}