Java Code Examples for reactor.util.context.Context#of()

The following examples show how to use reactor.util.context.Context#of() . 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: FluxConcatMapTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void discardOnNextQueueReject() {
	List<Object> discarded = new ArrayList<>();
	AssertSubscriber<Object> discardSubscriber = new AssertSubscriber<>(
			Context.of(Hooks.KEY_ON_DISCARD, (Consumer<?>) discarded::add));

	final CoreSubscriber<Object> subscriber =
			FluxConcatMap.subscriber(discardSubscriber,
					Mono::just,
					Queues.get(0),
					1,
					FluxConcatMap.ErrorMode.IMMEDIATE);
	subscriber.onSubscribe(Operators.emptySubscription());

	subscriber.onNext(1);

	assertThat(discarded).containsExactly(1);
}
 
Example 2
Source File: FluxDoOnEachTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void nextCompleteAndErrorHaveContext() {
	Context context = Context.of("foo", "bar");
	List<Signal> signals = new ArrayList<>();

	StepVerifier.create(Flux.just("hello")
	                        .doOnEach(signals::add),
			StepVerifierOptions.create().withInitialContext(context))
	            .expectNext("hello")
	            .verifyComplete();

	assertThat(signals)
	          .allSatisfy(signal -> assertThat(signal.getContext().hasKey("foo"))
			          .as("has Context value")
			          .isTrue());
}
 
Example 3
Source File: OperatorsTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void onNextErrorModeLocalStrategy() {
	List<Object> nextDropped = new ArrayList<>();
	List<Object> errorDropped = new ArrayList<>();
	Hooks.onNextDropped(nextDropped::add);
	Hooks.onErrorDropped(errorDropped::add);
	Hooks.onNextError(OnNextFailureStrategy.STOP);

	Context c = Context.of(OnNextFailureStrategy.KEY_ON_NEXT_ERROR_STRATEGY, OnNextFailureStrategy.RESUME_DROP);
	Exception error = new IllegalStateException("boom");
	DeferredSubscription s = new Operators.DeferredSubscription();

	assertThat(s.isCancelled()).as("s initially cancelled").isFalse();

	Throwable e = Operators.onNextError("foo", error, c, s);
	assertThat(e).isNull();
	assertThat(nextDropped).containsExactly("foo");
	assertThat(errorDropped).containsExactly(error);
	assertThat(s.isCancelled()).as("s cancelled").isFalse();
}
 
Example 4
Source File: FluxBufferWhenTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void discardOnCancelPostQueueing() {
	List<Object> discarded = new ArrayList<>();

	CoreSubscriber<List<Integer>> actual = new AssertSubscriber<>(
			Context.of(Hooks.KEY_ON_DISCARD, (Consumer<?>) discarded::add));
	FluxBufferWhen.BufferWhenMainSubscriber<Integer, Integer, Integer, List<Integer>> operator =
			new FluxBufferWhen.BufferWhenMainSubscriber<Integer, Integer, Integer, List<Integer>>(actual,
					ArrayList::new,
					Queues.small(),
					Flux.just(1), i -> Flux.never());
	operator.onSubscribe(new Operators.EmptySubscription());

	operator.buffers.put(0L, Arrays.asList(4, 5));
	operator.queue.offer(Arrays.asList(1, 2, 3));
	operator.cancel();

	assertThat(discarded).containsExactly(1, 2, 3, 4, 5);
}
 
Example 5
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeAbleToCancelSubscription() throws InterruptedException {
    Flux<Long> publisher = Flux.just(1L);
    ArrayList<Integer> capturedElementsNumber = new ArrayList<>();
    for (int i = 0; i < 10000; i++) {
        final ArrayList<Throwable> dropped = new ArrayList<>();
        final AtomicLong requested = new AtomicLong();
        final CountDownLatch latch = new CountDownLatch(1);
        final AssertSubscriber<Long> assertSubscriber = new AssertSubscriber<>(Context.of(Hooks.KEY_ON_ERROR_DROPPED, (Consumer<Throwable>) dropped::add), 0);
        final Flux<Long> switchTransformed = publisher
                                                .doOnRequest(requested::addAndGet)
                                                .doOnCancel(latch::countDown)
                                                .switchOnFirst((first, innerFlux) -> innerFlux.doOnComplete(latch::countDown));

        switchTransformed.subscribe(assertSubscriber);

        RaceTestUtils.race(assertSubscriber::cancel, () -> assertSubscriber.request(1));

        Assertions.assertThat(latch.await(500, TimeUnit.SECONDS)).isTrue();

        capturedElementsNumber.add(assertSubscriber.values().size());
    }

    Assumptions.assumeThat(capturedElementsNumber).contains(0);
    Assumptions.assumeThat(capturedElementsNumber).contains(1);
}
 
Example 6
Source File: FluxBufferWhenTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void discardOnDrainDoneWithErrors() {
	List<Object> discarded = new ArrayList<>();

	CoreSubscriber<List<Integer>> actual = new AssertSubscriber<>(
			Context.of(Hooks.KEY_ON_DISCARD, (Consumer<?>) discarded::add));
	FluxBufferWhen.BufferWhenMainSubscriber<Integer, Integer, Integer, List<Integer>> operator =
			new FluxBufferWhen.BufferWhenMainSubscriber<Integer, Integer, Integer, List<Integer>>(actual,
					ArrayList::new,
					Queues.small(),
					Flux.just(1), i -> Flux.never());
	operator.onSubscribe(new Operators.EmptySubscription());
	operator.request(1);

	operator.buffers.put(0L, Arrays.asList(4, 5));
	operator.queue.offer(Arrays.asList(1, 2, 3));
	operator.onError(new IllegalStateException("boom")); //triggers the drain

	assertThat(discarded).containsExactly(1, 2, 3, 4, 5);
}
 
Example 7
Source File: StepVerifierAssertionsTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void contextDiscardCaptureWithInitialContext() {
	Context initial = Context.of("foo", "bar");
	StepVerifier.create(Mono.subscriberContext()
			.flatMapIterable(ctx -> ctx.stream()
			                           .map(Map.Entry::getKey)
			                           .map(String::valueOf)
			                           .collect(Collectors.toList())
	                        ).concatWithValues("A", "B")
	                        .filter(s -> s.length() > 1)
			, StepVerifierOptions.create().withInitialContext(initial))
	            .expectNext("foo")
	            .expectNext("reactor.onDiscard.local")
	            .expectComplete()
	            .verifyThenAssertThat()
	            .hasDiscardedExactly("A", "B");
}
 
Example 8
Source File: WingtipsSpringWebfluxUtilsTest.java    From wingtips with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void tracingStateFromContext_works_as_expected(boolean contextHasTracingState) {
    // given
    TracingState tracingStateMock = mock(TracingState.class);
    Context context = (contextHasTracingState)
                      ? Context.of(TracingState.class, tracingStateMock)
                      : Context.empty();

    TracingState expectedResult = (contextHasTracingState) ? tracingStateMock : null;

    // when
    TracingState result = WingtipsSpringWebfluxUtils.tracingStateFromContext(context);

    // then
    assertThat(result).isEqualTo(expectedResult);
}
 
Example 9
Source File: DefaultContextExpectationsTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void notContainsOnlyOfContextSize() throws Exception {
	Context expected = Context.of("foo", "bar", "other", "stuff");

	assertContextExpectationFails(s -> s.subscriberContext(Context.of("foo", "bar")),
			e -> e.containsOnly(expected))
			.withMessage("Expected Context Context1{foo=bar} to contain same values as " +
					"Context2{foo=bar, other=stuff}, but they differ in size");
}
 
Example 10
Source File: DefaultContextExpectationsTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void notContainsOnlyOfContextContent() throws Exception {
	Context expected = Context.of("foo", "bar", "other", "stuff");

	assertContextExpectationFails(s -> s.subscriberContext(Context.of("foo", "bar", "foobar", "baz")),
			e -> e.containsOnly(expected))
			.withMessage("Expected Context Context2{foo=bar, foobar=baz} to contain " +
					"same values as Context2{foo=bar, other=stuff}, but they differ in content");
}
 
Example 11
Source File: RequestHelper.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
public Context createContext(String apiCall, org.glassfish.grizzly.http.server.Request request)
{
    final String userAgent = request.getHeader("User-Agent");
    Peer peer = new PeerREST(request.getRemoteAddr(), userAgent, publicContext);

    checkLDAPAuth(peer, request.getAuthorization());

    errorReporter.logDebug("REST access api '%s' from '%s'", apiCall, peer.toString());
    return  Context.of(
        ApiModule.API_CALL_NAME, apiCall,
        AccessContext.class, peer.getAccessContext(),
        Peer.class, peer
    );
}
 
Example 12
Source File: FluxFilterTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void discardTryOnNextPredicateFail() {
	List<Object> discarded = new ArrayList<>();
	CoreSubscriber<Integer> actual = new AssertSubscriber<>(
			Context.of(Hooks.KEY_ON_DISCARD, (Consumer<?>) discarded::add));
	FilterSubscriber<Integer> subscriber =
			new FilterSubscriber<>(actual, i -> { throw new IllegalStateException("boom"); });
	subscriber.onSubscribe(Operators.emptySubscription());

	subscriber.tryOnNext(1);

	assertThat(discarded).containsExactly(1);
}
 
Example 13
Source File: SignalTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void nextStateWithContext(){
	Context context = Context.of("foo", "bar");
	Signal<Integer> s = Signal.next(1, context);

	assertThat(s.getContext().isEmpty()).as("has context").isFalse();

	assertThat(s.isOnComplete()).isFalse();
	assertThat(s.isOnSubscribe()).isFalse();
	assertThat(s.hasError()).isFalse();
	assertThat(s.hasValue()).isTrue();

	assertThat(s).isEqualTo(Signal.next(1));
	assertThat(s).isNotEqualTo(Signal.next(2));
	assertThat(s).isNotEqualTo(Signal.error(e));
	assertThat(s).isNotEqualTo(Signal.complete());
	assertThat(s).isNotEqualTo(Signal.subscribe(Operators.emptySubscription()));
	assertThat(s.hashCode()).isEqualTo(Signal.next(1).hashCode());
	assertThat(s.hashCode()).isNotEqualTo(Signal.next(2).hashCode());
	assertThat(s.hashCode()).isNotEqualTo(Signal.error(e).hashCode());
	assertThat(s.hashCode()).isNotEqualTo(Signal.complete().hashCode());
	assertThat(s.hashCode()).isNotEqualTo(Signal.subscribe(Operators.emptySubscription()).hashCode());

	assertThat(Signal.isComplete(s)).isFalse();
	assertThat(Signal.isError(s)).isFalse();
	assertThat(s.get()).isEqualTo(1);

	assertThat(s.getType()).isEqualTo(SignalType.ON_NEXT);
	assertThat(s.toString()).contains("onNext(1)");

	StepVerifier.create(Flux.<Integer>from(sub -> {
		sub.onSubscribe(Operators.emptySubscription());
		s.accept(sub);
	}))
	            .expectNext(1)
	            .thenCancel()
	            .verify();
}
 
Example 14
Source File: ScopePassingSpanSubscriberTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Test
public void should_propagate_current_context() {
	ScopePassingSpanSubscriber<?> subscriber = new ScopePassingSpanSubscriber<>(null,
			Context.of("foo", "bar"), this.currentTraceContext, null);

	then((String) subscriber.currentContext().get("foo")).isEqualTo("bar");
}
 
Example 15
Source File: LambdaSubscriberTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void initialContextIsUsedForOnErrorDropped() {
	AtomicReference<Throwable> droppedRef = new AtomicReference<>();
	Context ctx = Context.of(Hooks.KEY_ON_ERROR_DROPPED, (Consumer<Throwable>) droppedRef::set);
	IllegalStateException expectDropped = new IllegalStateException("boom2");
	LambdaSubscriber<Object> sub = new LambdaSubscriber<>(null, e -> { }, null, null, ctx);

	sub.onError(new IllegalStateException("boom1"));
	//now trigger drop
	sub.onError(expectDropped);

	assertThat(droppedRef).hasValue(expectDropped);
}
 
Example 16
Source File: LambdaMonoSubscriberTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void initialContextIsUsedForOnErrorDropped() {
	AtomicReference<Throwable> droppedRef = new AtomicReference<>();
	Context ctx = Context.of(Hooks.KEY_ON_ERROR_DROPPED, (Consumer<Throwable>) droppedRef::set);
	IllegalStateException expectDropped = new IllegalStateException("boom2");
	LambdaMonoSubscriber<Object> sub = new LambdaMonoSubscriber<>(null, e -> { }, null, null, ctx);

	sub.onError(new IllegalStateException("boom1"));
	//now trigger drop
	sub.onError(expectDropped);

	Assertions.assertThat(droppedRef).hasValue(expectDropped);
}
 
Example 17
Source File: FluxPeekFuseableTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void resumeFuseableConditional() {
	RuntimeException nextError = new IllegalStateException("next");
	List<Throwable> resumedErrors = new ArrayList<>();
	List<Object> resumedValues = new ArrayList<>();
	Context context = Context.of(OnNextFailureStrategy.KEY_ON_NEXT_ERROR_STRATEGY,
								 OnNextFailureStrategy.resume((t, s) -> {
									 resumedErrors.add(t);
									 resumedValues.add(s);
								 }));

	ConditionalAssertSubscriber<Integer> actual = new ConditionalAssertSubscriber<>(context);
	SignalPeekThrowNext<Integer> peekParent = new SignalPeekThrowNext<>(nextError);
	AssertQueueSubscription<Integer> qs = new AssertQueueSubscription<>();

	PeekFuseableConditionalSubscriber<Integer> test = new PeekFuseableConditionalSubscriber<>(actual, peekParent);
	test.onSubscribe(qs);

	test.onNext(1);
	assertThat(actual.next).as("onNext skips").isEmpty();
	assertThat(qs.requested).as("onNext requested more").isEqualTo(1);

	boolean tryOnNext = test.tryOnNext(2);
	assertThat(tryOnNext).as("tryOnNext skips").isFalse();

	qs.offer(3);
	Integer polled = test.poll();
	assertThat(polled).as("poll skips").isNull();

	test.onComplete();

	assertThat(actual.error).isNull();
	assertThat(actual.completed).isTrue();

	assertThat(resumedErrors).containsExactly(nextError, nextError, nextError);
	assertThat(resumedValues).containsExactly(1, 2, 3);
}
 
Example 18
Source File: OperatorsTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void onNextDroppedLocal() {
	AtomicReference<Object> hookState = new AtomicReference<>();
	Consumer<Object> localHook = hookState::set;
	Context c = Context.of(Hooks.KEY_ON_NEXT_DROPPED, localHook);

	Operators.onNextDropped("foo", c);

	assertThat(hookState.get()).isEqualTo("foo");
}
 
Example 19
Source File: ReactorUtils.java    From james-project with Apache License 2.0 4 votes vote down vote up
public static Context context(String keySuffix, MDCBuilder mdcBuilder) {
    return Context.of(mdcKey(keySuffix), mdcBuilder);
}
 
Example 20
Source File: Operators.java    From reactor-core with Apache License 2.0 3 votes vote down vote up
/**
 * Utility method to activate the onDiscard feature (see {@link Flux#doOnDiscard(Class, Consumer)})
 * in a target {@link Context}. Prefer using the {@link Flux} API, and reserve this for
 * testing purposes.
 *
 * @param target the original {@link Context}
 * @param discardConsumer the consumer that will be used to cleanup discarded elements
 * @return a new {@link Context} that holds (potentially combined) cleanup {@link Consumer}
 */
public static final Context enableOnDiscard(@Nullable Context target, Consumer<?> discardConsumer) {
	Objects.requireNonNull(discardConsumer, "discardConsumer must be provided");
	if (target == null) {
		return Context.of(Hooks.KEY_ON_DISCARD, discardConsumer);
	}
	return target.put(Hooks.KEY_ON_DISCARD, discardConsumer);
}