reactor.core.publisher.Hooks Java Examples

The following examples show how to use reactor.core.publisher.Hooks. 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: ReactorTestExecutionListener.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
public static void reset() {
	Hooks.resetOnOperatorDebug();

	Hooks.resetOnEachOperator();
	Hooks.resetOnLastOperator();

	Hooks.resetOnErrorDropped();
	Hooks.resetOnNextDropped();

	Hooks.resetOnNextError();
	Hooks.resetOnOperatorError();

	Schedulers.resetOnHandleError();
	Schedulers.resetFactory();
	Schedulers.resetOnScheduleHooks();

	// TODO capture non-default schedulers and shutdown them
}
 
Example #2
Source File: FluxAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void enter() {
  if (inited.get())
    return;

  synchronized (inited) {
    if (inited.get())
      return;

    try {
      Operators.class.getMethod("liftPublisher", BiFunction.class);
    }
    catch (final NoSuchMethodException e) {
      logger.warning("Reactor version is not supported");
      inited.set(true);
      return;
    }

    final Tracer tracer = GlobalTracer.get();
    Hooks.onEachOperator(TracedSubscriber.asOperator(tracer));
    Hooks.onLastOperator(TracedSubscriber.asOperator(tracer));
    inited.set(true);
  }
}
 
Example #3
Source File: ParallelFluxAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void enter() {
  if (inited.get())
    return;

  synchronized (inited) {
    if (inited.get())
      return;

    try {
      Operators.class.getMethod("liftPublisher", BiFunction.class);
    }
    catch (final NoSuchMethodException e) {
      logger.warning("Reactor version is not supported");
      inited.set(true);
      return;
    }

    final Tracer tracer = GlobalTracer.get();
    Hooks.onEachOperator(TracedSubscriber.asOperator(tracer));
    Hooks.onLastOperator(TracedSubscriber.asOperator(tracer));
    inited.set(true);
  }
}
 
Example #4
Source File: MonoAgentIntercept.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void enter() {
  if (inited.get())
    return;

  synchronized (inited) {
    if (inited.get())
      return;

    try {
      Operators.class.getMethod("liftPublisher", BiFunction.class);
    }
    catch (final NoSuchMethodException e) {
      logger.warning("Reactor version is not supported");
      inited.set(true);
      return;
    }

    final Tracer tracer = GlobalTracer.get();
    Hooks.onEachOperator(TracedSubscriber.asOperator(tracer));
    Hooks.onLastOperator(TracedSubscriber.asOperator(tracer));
    inited.set(true);
  }
}
 
Example #5
Source File: ReactivePostRepositoryTest.java    From POC with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setUp() {

	Hooks.onOperatorDebug();

	List<String> statements = Arrays.asList(//
			"DROP TABLE IF EXISTS reactive_posts;",
			"CREATE TABLE reactive_posts ( id SERIAL PRIMARY KEY, title VARCHAR(100) NOT NULL, content VARCHAR(100) NOT NULL);");

	statements.forEach(it -> this.databaseClient.execute(it) //
			.fetch() //
			.rowsUpdated() //
			.as(StepVerifier::create) //
			.expectNextCount(1) //
			.verifyComplete());
}
 
Example #6
Source File: FluxDiscardOnCancelTest.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
@Test
void assemblyHook() {
    List<Object> publishers = new ArrayList<>();
    Hooks.onEachOperator(objectPublisher -> {
        publishers.add(objectPublisher);

        return objectPublisher;
    });

    Iterator<Integer> items = createItems(5);
    Flux<Integer> flux = Flux.fromIterable(() -> items);

    flux.transform(OperatorUtils::discardOnCancel)
        .as(StepVerifier::create)
        .expectNextCount(5)
        .verifyComplete();

    ObjectAssert<?> element = assertThat(publishers).hasSize(2).element(1);

    if (flux instanceof Fuseable) {
        element.isExactlyInstanceOf(FluxDiscardOnCancelFuseable.class);
    } else {
        element.isExactlyInstanceOf(FluxDiscardOnCancel.class);
    }
}
 
Example #7
Source File: FluxDiscardOnCancelTest.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
@Test
void assemblyHook() {
    List<Object> publishers = new ArrayList<>();
    Hooks.onEachOperator(objectPublisher -> {
        publishers.add(objectPublisher);

        return objectPublisher;
    });

    Iterator<Integer> items = createItems(5);
    Flux<Integer> flux = Flux.fromIterable(() -> items);

    flux.transform(OperatorUtils::discardOnCancel)
        .as(StepVerifier::create)
        .expectNextCount(5)
        .verifyComplete();

    ObjectAssert<?> element = assertThat(publishers).hasSize(2).element(1);

    if (flux instanceof Fuseable) {
        element.isExactlyInstanceOf(FluxDiscardOnCancelFuseable.class);
    } else {
        element.isExactlyInstanceOf(FluxDiscardOnCancel.class);
    }
}
 
Example #8
Source File: ReactiveRequestProcessingTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void getTasks() throws IOException {
	Mockito.when(requestContextBase.getMethod()).thenReturn("GET");
	Mockito.when(requestContextBase.getPath()).thenReturn("/reactive/task/");
	Mockito.when(requestContextBase.getRequestHeader("Accept")).thenReturn("*");
	Hooks.onOperatorDebug();
	HttpResponse response = processor.processAsync(requestContext).get();

	String json = new String(response.getBody());
	Assert.assertEquals(200, response.getStatusCode());
	Document document = boot.getObjectMapper().readerFor(Document.class).readValue(json);
	Assert.assertTrue(document.getData().isPresent());

	List<Resource> resources = document.getCollectionData().get();
	Assert.assertEquals(1, resources.size());
	Resource resource = resources.get(0);
	Assert.assertEquals("http://localhost:8080/reactive/task/1", resource.getLinks().get("self").asText());
	Assert.assertNotNull(resource.getLinks().get("value"));
}
 
Example #9
Source File: GuideDebuggingExtraTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void debuggingActivatedWithDeepTraceback() {
	Hooks.onOperatorDebug();

	StringWriter sw = new StringWriter();
	FakeRepository.findAllUserByName(Flux.just("pedro", "simon", "stephane"))
	              .transform(FakeUtils1.applyFilters)
	              .transform(FakeUtils2.enrichUser)
	              .subscribe(System.out::println,
			              t -> t.printStackTrace(new PrintWriter(sw))
	              );

	String debugStack = sw.toString();

	assertThat(debugStack.substring(0, debugStack.indexOf("Stack trace:")))
			.endsWith("Error has been observed at the following site(s):\n"
					+ "\t|_       Flux.map ⇢ at reactor.guide.FakeRepository.findAllUserByName(FakeRepository.java:27)\n"
					+ "\t|_       Flux.map ⇢ at reactor.guide.FakeRepository.findAllUserByName(FakeRepository.java:28)\n"
					+ "\t|_    Flux.filter ⇢ at reactor.guide.FakeUtils1.lambda$static$1(FakeUtils1.java:29)\n"
					+ "\t|_ Flux.transform ⇢ at reactor.guide.GuideDebuggingExtraTests.debuggingActivatedWithDeepTraceback(GuideDebuggingExtraTests.java:40)\n"
					+ "\t|_   Flux.elapsed ⇢ at reactor.guide.FakeUtils2.lambda$static$0(FakeUtils2.java:30)\n"
					+ "\t|_ Flux.transform ⇢ at reactor.guide.GuideDebuggingExtraTests.debuggingActivatedWithDeepTraceback(GuideDebuggingExtraTests.java:41)\n");
}
 
Example #10
Source File: CustomerRepositoryIntegrationTests.java    From spring-data-examples with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {

	Hooks.onOperatorDebug();

	List<String> statements = Arrays.asList(//
			"DROP TABLE IF EXISTS customer;",
			"CREATE TABLE customer ( id SERIAL PRIMARY KEY, firstname VARCHAR(100) NOT NULL, lastname VARCHAR(100) NOT NULL);");

	statements.forEach(it -> database.execute(it) //
			.fetch() //
			.rowsUpdated() //
			.as(StepVerifier::create) //
			.expectNextCount(1) //
			.verifyComplete());
}
 
Example #11
Source File: HooksTraceTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testTrace2() {
	Hooks.onOperatorDebug();

	assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
		Mono.just(1)
		    .map(d -> {
			    throw new RuntimeException();
		    })
		    .filter(d -> true)
		    .doOnNext(d -> System.currentTimeMillis())
		    .map(d -> d)
		    .block()
	).satisfies(e -> assertThat(e.getSuppressed()[0])
			.hasMessageContaining("HooksTraceTest.java:")
			.hasMessageContaining("|_      Mono.map ⇢ at reactor.HooksTraceTest.lambda$testTrace2$8(HooksTraceTest.java:")
	);
}
 
Example #12
Source File: HooksTraceTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testTrace3() {
	Hooks.onOperatorDebug();
	assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
			Flux.just(1)
			    .map(d -> {
				    throw new RuntimeException();
			    })
			    .share()
			    .filter(d -> true)
			    .doOnNext(d -> System.currentTimeMillis())
			    .map(d -> d)
			    .blockLast()
	).satisfies(e -> assertThat(e.getSuppressed()[0])
			.hasMessageContaining("HooksTraceTest.java:")
			.hasMessageContaining("|_    Flux.share ⇢ at reactor.HooksTraceTest.lambda$testTrace3$14(HooksTraceTest.java:")
	);
}
 
Example #13
Source File: TraceReactorAutoConfiguration.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
static void setupHooks(ConfigurableApplicationContext springContext) {
	ConfigurableEnvironment environment = springContext.getEnvironment();
	boolean decorateOnEach = environment.getProperty(
			"spring.sleuth.reactor.decorate-on-each", Boolean.class, true);
	if (decorateOnEach) {
		if (log.isTraceEnabled()) {
			log.trace("Decorating onEach operator instrumentation");
		}
		Hooks.onEachOperator(SLEUTH_TRACE_REACTOR_KEY,
				scopePassingSpanOperator(springContext));
	}
	else {
		if (log.isTraceEnabled()) {
			log.trace("Decorating onLast operator instrumentation");
		}
		Hooks.onLastOperator(SLEUTH_TRACE_REACTOR_KEY,
				scopePassingSpanOperator(springContext));
	}
	Schedulers.setExecutorServiceDecorator(
			TraceReactorAutoConfiguration.SLEUTH_REACTOR_EXECUTOR_SERVICE_KEY,
			(scheduler,
					scheduledExecutorService) -> new TraceableScheduledExecutorService(
							springContext, scheduledExecutorService));
}
 
Example #14
Source File: HooksTraceTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testTraceComposed2() {
	Hooks.onOperatorDebug();
	assertThatExceptionOfType(RuntimeException.class).isThrownBy(() ->
			Flux.just(1)
			    .flatMap(d -> {
				    throw new RuntimeException();
			    })
			    .filter(d -> true)
			    .doOnNext(d -> System.currentTimeMillis())
			    .map(d -> d)
			    .blockLast()
	).satisfies(e -> assertThat(e.getSuppressed()[0])
			.hasMessageContaining("HooksTraceTest.java:")
			.hasMessageContaining("|_  Flux.flatMap ⇢ at reactor.HooksTraceTest.lambda$testTraceComposed2$31(HooksTraceTest.java:")
	);
}
 
Example #15
Source File: HooksTraceTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void testOnLastPublisher() {
	List<Publisher> l = new ArrayList<>();
	Hooks.onLastOperator(p -> {
		System.out.println(Scannable.from(p).parents().count());
		System.out.println(Scannable.from(p).stepName());
		l.add(p);
		return p;
	});
	StepVerifier.create(Flux.just(1, 2, 3)
	                        .map(m -> m)
	                        .takeUntilOther(Mono.never())
	                        .flatMap(d -> Mono.just(d).hide()))
	            .expectNext(1, 2, 3)
	            .verifyComplete();

	assertThat(l).hasSize(5);
}
 
Example #16
Source File: TraceReactorAutoConfiguration.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@PreDestroy
public void cleanupHooks() {
	if (log.isTraceEnabled()) {
		log.trace("Cleaning up hooks");
	}
	SleuthReactorProperties reactorProperties = this.springContext
			.getBean(SleuthReactorProperties.class);
	if (reactorProperties.isDecorateOnEach()) {
		if (log.isTraceEnabled()) {
			log.trace("Resetting onEach operator instrumentation");
		}
		Hooks.resetOnEachOperator(SLEUTH_TRACE_REACTOR_KEY);
	}
	else {
		if (log.isTraceEnabled()) {
			log.trace("Resetting onLast operator instrumentation");
		}
		Hooks.resetOnLastOperator(SLEUTH_TRACE_REACTOR_KEY);
	}
	Schedulers
			.removeExecutorServiceDecorator(SLEUTH_REACTOR_EXECUTOR_SERVICE_KEY);
}
 
Example #17
Source File: R2dbcApplicationIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Before
public void setup() {

    Hooks.onOperatorDebug();

    List<String> statements = Arrays.asList(//
            "DROP TABLE IF EXISTS player;",
            "CREATE table player (id INT AUTO_INCREMENT NOT NULL, name VARCHAR2, age INT NOT NULL);");

    statements.forEach(it -> client.execute(it) //
            .fetch() //
            .rowsUpdated() //
            .as(StepVerifier::create) //
            .expectNextCount(1) //
            .verifyComplete());

}
 
Example #18
Source File: RejectedExecutionTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
	scheduler = new BoundedScheduler(Schedulers.newSingle("bounded-single"));
	Hooks.onNextDropped(o -> onNextDropped.add(o));
	Hooks.onErrorDropped(e -> onErrorDropped.add(e));
	Hooks.onOperatorError((e, o) -> {
		onOperatorError.add(e);
		if (o instanceof Long)
			onOperatorErrorData.add((Long) o);
		else if (o != null) {
			System.out.println(o);
		}
		return e;
	});
	Schedulers.onHandleError((thread, t) -> onSchedulerHandleError.add(t));
}
 
Example #19
Source File: FluxTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void fluxFromMonoNormalCallsAssemblyHook() {
	final Mono<String> source = Mono.just("monoNormal")
	                                .hide()
	                                .map(i -> i);

	//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
	AtomicInteger wrappedCount = new AtomicInteger();
	Hooks.onEachOperator(p -> {
		wrappedCount.incrementAndGet();
		return p;
	});

	Flux.from(source);
	Assertions.assertThat(wrappedCount).hasValue(1);
}
 
Example #20
Source File: FluxTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void fluxNextCallableCallsAssemblyHook() {
	Flux<Integer> source = Mono.fromCallable(() -> 1).flux();
	Assertions.assertThat(source) //smoke test that we go into the right case
	          .isInstanceOf(Callable.class)
	          .isNotInstanceOf(Mono.class)
	          .isNotInstanceOf(Fuseable.ScalarCallable.class);

	//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
	AtomicInteger wrappedCount = new AtomicInteger();
	Hooks.onEachOperator(p -> {
		wrappedCount.incrementAndGet();
		return p;
	});

	source.next();
	Assertions.assertThat(wrappedCount).hasValue(1);
}
 
Example #21
Source File: FluxTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void fluxNextScalarEmptyCallsAssemblyHook() {
	Flux<Integer> source = Flux.empty();

	//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
	AtomicInteger wrappedCount = new AtomicInteger();
	Hooks.onEachOperator(p -> {
		wrappedCount.incrementAndGet();
		return p;
	});

	source.next();
	Assertions.assertThat(wrappedCount).hasValue(1);
}
 
Example #22
Source File: MonoTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void monoFromDirectFluxCallsAssemblyHook() {
	final Flux<Integer> source = Flux.just(1).hide();

	//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
	AtomicInteger wrappedCount = new AtomicInteger();
	Hooks.onEachOperator(p -> {
		wrappedCount.incrementAndGet();
		return p;
	});

	Mono.fromDirect(source);
	Assertions.assertThat(wrappedCount).hasValue(1);
}
 
Example #23
Source File: MonoTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void monoFromDirectCallableFluxCallsAssemblyHook() {
	final Flux<Integer> source = Flux.just(1);

	//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
	AtomicInteger wrappedCount = new AtomicInteger();
	Hooks.onEachOperator(p -> {
		wrappedCount.incrementAndGet();
		return p;
	});

	Mono.fromDirect(source);
	Assertions.assertThat(wrappedCount).hasValue(1);
}
 
Example #24
Source File: MonoTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void monoFromDirectFluxWrappingMonoDoesntCallAssemblyHook() {
	final Flux<Integer> source = Flux.from(Mono.just(1).hide());

	//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
	AtomicInteger wrappedCount = new AtomicInteger();
	Hooks.onEachOperator(p -> {
		wrappedCount.incrementAndGet();
		return p;
	});

	Mono.fromDirect(source);
	Assertions.assertThat(wrappedCount).hasValue(0);
}
 
Example #25
Source File: MonoTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void monoFromDirectMonoDoesntCallAssemblyHook() {
	final Mono<Integer> source = Mono.just(1);

	//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
	AtomicInteger wrappedCount = new AtomicInteger();
	Hooks.onEachOperator(p -> {
		wrappedCount.incrementAndGet();
		return p;
	});

	Mono.fromDirect(source);
	Assertions.assertThat(wrappedCount).hasValue(0);
}
 
Example #26
Source File: MonoTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void monoFromPublisherCallsAssemblyHook() {
	final Publisher<Integer> source = TestPublisher.create();
	Assertions.assertThat(source).isNotInstanceOf(Flux.class); //smoke test this is a Publisher

	//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
	AtomicInteger wrappedCount = new AtomicInteger();
	Hooks.onEachOperator(p -> {
		wrappedCount.incrementAndGet();
		return p;
	});

	Mono.from(source);
	Assertions.assertThat(wrappedCount).hasValue(1);
}
 
Example #27
Source File: MonoTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void monoFromFluxCallsAssemblyHook() {
	final Flux<Integer> source = Flux.just(1).hide();

	//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
	AtomicInteger wrappedCount = new AtomicInteger();
	Hooks.onEachOperator(p -> {
		wrappedCount.incrementAndGet();
		return p;
	});

	Mono.from(source);
	Assertions.assertThat(wrappedCount).hasValue(1);
}
 
Example #28
Source File: MonoTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void monoFromCallableFluxCallsAssemblyHook() {
	final Flux<Integer> source = Flux.just(1);

	//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
	AtomicInteger wrappedCount = new AtomicInteger();
	Hooks.onEachOperator(p -> {
		wrappedCount.incrementAndGet();
		return p;
	});

	Mono.from(source);
	Assertions.assertThat(wrappedCount).hasValue(1);
}
 
Example #29
Source File: MonoTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void monoFromFluxWrappingMonoDoesntCallAssemblyHook() {
	final Flux<Integer> source = Flux.from(Mono.just(1).hide());

	//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
	AtomicInteger wrappedCount = new AtomicInteger();
	Hooks.onEachOperator(p -> {
		wrappedCount.incrementAndGet();
		return p;
	});

	Mono.from(source);
	Assertions.assertThat(wrappedCount).hasValue(0);
}
 
Example #30
Source File: MonoTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void monoFromDirectPublisherCallsAssemblyHook() {
	final Publisher<Integer> source = TestPublisher.create();
	Assertions.assertThat(source).isNotInstanceOf(Flux.class); //smoke test this is a Publisher

	//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
	AtomicInteger wrappedCount = new AtomicInteger();
	Hooks.onEachOperator(p -> {
		wrappedCount.incrementAndGet();
		return p;
	});

	Mono.fromDirect(source);
	Assertions.assertThat(wrappedCount).hasValue(1);
}