Java Code Examples for reactor.core.publisher.MonoProcessor#block()

The following examples show how to use reactor.core.publisher.MonoProcessor#block() . 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: EmployeeHotStreamServiceImpl.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
@Override
public void monoProcessorGetEmployee(Integer id) {
	MonoProcessor<Integer> future = MonoProcessor.create();
	Consumer<Integer> checkEmp = (rowId) ->{
		if(employeeDaoImpl.getEmployee(rowId) == null){
			System.out.println("Employee with id: " + rowId + " does not exists.");
		}else{
			System.out.println("Employee with id: " + rowId + " exists.");
		}
	};
	
	Mono<Integer> engine = future
		    .doOnNext(checkEmp)
	     	.doOnSuccess(emp -> {
				System.out.println("Employee's age is " + employeeDaoImpl.getEmployee(emp).getAge());
				System.out.println("Employee's dept is: " + employeeDaoImpl.getEmployee(emp).getDeptId());
			})
	        .doOnTerminate((sup, ex) -> System.out.println("Transaction terminated with error: " +ex.getMessage()))
	        .doOnError(ex -> System.out.println("Error: " + ex.getMessage()));
	
	engine.subscribe(System.out::println);
	
	future.onNext(id);
	int valStream = future.block();
	System.out.println("Employee's ID again is: " + valStream);
}
 
Example 2
Source File: ReactorSerializedInvoker.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
public void shutdown(Duration timeout) {
    if (shutdownFlag) {
        return;
    }

    this.shutdownFlag = true;
    MonoProcessor<Void> marker = MonoProcessor.create();
    worker.schedule(this::drainOnShutdown);
    worker.schedule(marker::onComplete);

    try {
        marker.block(timeout);
    } catch (Exception ignoreTimeout) {
    } finally {
        worker.dispose();
    }
}
 
Example 3
Source File: FluxSpecTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
	public void streamValuesCanBeExploded() {
//		Stream"s values can be exploded
//			given: "a source composable with a mapMany function"
		FluxIdentityProcessor<Integer> source = Processors.multicast();
		Flux<Integer> mapped = source
				.log()
				.publishOn(Schedulers.parallel())
				.log()
				.flatMap(v -> Flux.just(v * 2))
				.doOnError(Throwable::printStackTrace);

//			when: "the source accepts a value"
		MonoProcessor<Integer> value = mapped.next()
		                                     .toProcessor();
		value.subscribe();
		source.sink().next(1);

//		then: "the value is mapped"
		int result = value.block(Duration.ofSeconds(5));
		assertThat(result).isEqualTo(2);
	}
 
Example 4
Source File: TcpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testChannelGroupClosesAllConnections() throws Exception {
	MonoProcessor<Void> serverConnDisposed = MonoProcessor.create();

	ChannelGroup group = new DefaultChannelGroup(new DefaultEventExecutor());

	CountDownLatch latch = new CountDownLatch(1);

	DisposableServer boundServer =
			TcpServer.create()
			         .port(0)
			         .doOnConnection(c -> {
			             c.onDispose()
			              .subscribe(serverConnDisposed);
			             group.add(c.channel());
			             latch.countDown();
			         })
			         .wiretap(true)
			         .bindNow();

	TcpClient.create()
	         .remoteAddress(boundServer::address)
	         .wiretap(true)
	         .connect()
	         .subscribe();

	assertTrue(latch.await(30, TimeUnit.SECONDS));

	boundServer.disposeNow();

	FutureMono.from(group.close())
	          .block(Duration.ofSeconds(30));

	serverConnDisposed.block(Duration.ofSeconds(5));
}
 
Example 5
Source File: TcpServerTests.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void sendFileSecure()
		throws CertificateException, SSLException, URISyntaxException {
	Path largeFile = Paths.get(getClass().getResource("/largeFile.txt").toURI());
	SelfSignedCertificate ssc = new SelfSignedCertificate();
	SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
	SslContext sslClient = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

	DisposableServer context =
			TcpServer.create()
			         .secure(spec -> spec.sslContext(sslServer))
			         .handle((in, out) ->
			                 in.receive()
			                   .asString()
			                   .flatMap(word -> "GOGOGO".equals(word) ?
			                            out.sendFile(largeFile).then() :
			                            out.sendString(Mono.just("NOPE"))))
			         .wiretap(true)
			         .bindNow();

	assertNotNull(context);

	MonoProcessor<String> m1 = MonoProcessor.create();
	MonoProcessor<String> m2 = MonoProcessor.create();

	Connection client1 =
			TcpClient.create()
			         .port(context.port())
			         .secure(spec -> spec.sslContext(sslClient))
			         .handle((in, out) -> {
			             in.receive()
			               .asString()
			               .log("-----------------CLIENT1")
			               .subscribe(m1::onNext);

			             return out.sendString(Mono.just("gogogo"))
			                       .neverComplete();
			         })
			         .wiretap(true)
			         .connectNow();

	Connection client2 =
			TcpClient.create()
			         .port(context.port())
			         .secure(spec -> spec.sslContext(sslClient))
			         .handle((in, out) -> {
			             in.receive()
			               .asString(StandardCharsets.UTF_8)
			               .takeUntil(d -> d.contains("<- 1024 mark here"))
			               .reduceWith(String::new, String::concat)
			               .log("-----------------CLIENT2")
			               .subscribe(m2::onNext);

			             return out.sendString(Mono.just("GOGOGO"))
			                       .neverComplete();
			         })
			         .wiretap(true)
			         .connectNow();

	assertNotNull(client2);

	String client1Response = m1.block();
	String client2Response = m2.block();

	client1.disposeNow();
	client2.disposeNow();
	context.disposeNow();

	Assertions.assertThat(client1Response).isEqualTo("NOPE");

	Assertions.assertThat(client2Response)
	          .startsWith("This is an UTF-8 file that is larger than 1024 bytes. " + "It contains accents like é.")
	          .contains("1024 mark here ->")
	          .contains("<- 1024 mark here")
	          .endsWith("End of File");
}
 
Example 6
Source File: TcpServerTests.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
private void assertSendFile(Function<NettyOutbound, NettyOutbound> fn) {
	DisposableServer context =
			TcpServer.create()
			         .handle((in, out) ->
			                 in.receive()
			                   .asString()
			                   .flatMap(word -> "GOGOGO".equals(word) ?
			                            fn.apply(out).then() :
			                            out.sendString(Mono.just("NOPE"))))
			         .wiretap(true)
			         .bindNow();

	assertNotNull(context);

	MonoProcessor<String> m1 = MonoProcessor.create();
	MonoProcessor<String> m2 = MonoProcessor.create();

	Connection client1 =
			TcpClient.create()
			         .port(context.port())
			         .handle((in, out) -> {
			             in.receive()
			               .asString()
			               .log("-----------------CLIENT1")
			               .subscribe(m1::onNext);

			             return out.sendString(Mono.just("gogogo"))
			                       .neverComplete();
			         })
			         .wiretap(true)
			         .connectNow();

	Connection client2 =
			TcpClient.create()
			         .port(context.port())
			         .handle((in, out) -> {
			             in.receive()
			               .asString(StandardCharsets.UTF_8)
			               .take(2)
			               .reduceWith(String::new, String::concat)
			               .log("-----------------CLIENT2")
			               .subscribe(m2::onNext);

			             return out.sendString(Mono.just("GOGOGO"))
			                       .neverComplete();
			         })
			         .wiretap(true)
			         .connectNow();

	assertNotNull(client2);

	String client1Response = m1.block();
	String client2Response = m2.block();

	client1.disposeNow();
	client2.disposeNow();
	context.disposeNow();

	Assertions.assertThat(client1Response).isEqualTo("NOPE");

	Assertions.assertThat(client2Response)
	          .startsWith("This is an UTF-8 file that is larger than 1024 bytes. " + "It contains accents like é.")
	          .contains("1024 mark here ->")
	          .contains("<- 1024 mark here")
	          .endsWith("End of File");
}
 
Example 7
Source File: FluxTests.java    From reactor-core with Apache License 2.0 4 votes vote down vote up
/**
 * <pre>
 *                 forkStream
 *                 /        \      < - - - int
 *                v          v
 * persistenceStream        computationStream
 *                 \        /      < - - - List< String >
 *                  v      v
 *                 joinStream      < - - - String
 *                 splitStream
 *             observedSplitStream
 * </pre>
    * @throws Exception for convenience
 */
@Test(timeout = TIMEOUT)
public void multiplexUsingDispatchersAndSplit() throws Exception {

	final FluxIdentityProcessor<Integer> forkEmitterProcessor = Processors.multicast();

	final FluxIdentityProcessor<Integer> computationEmitterProcessor = Processors.more().multicast(false);

	Scheduler computation = Schedulers.newSingle("computation");
	Scheduler persistence = Schedulers.newSingle("persistence");
	Scheduler forkJoin = Schedulers.newParallel("forkJoin", 2);

	final Flux<List<String>> computationStream =
			computationEmitterProcessor.publishOn(computation)
			                      .map(i -> {
				                      final List<String> list = new ArrayList<>(i);
				                      for (int j = 0; j < i; j++) {
					                      list.add("i" + j);
				                      }
				                      return list;
			                      })
			                      .doOnNext(ls -> println("Computed: ", ls))
			                      .log("computation");

	final FluxIdentityProcessor<Integer> persistenceEmitterProcessor = Processors.more().multicast(false);

	final Flux<List<String>> persistenceStream =
			persistenceEmitterProcessor.publishOn(persistence)
			                      .doOnNext(i -> println("Persisted: ", i))
			                      .map(i -> Collections.singletonList("done" + i))
			                      .log("persistence");

	Flux<Integer> forkStream = forkEmitterProcessor.publishOn(forkJoin)
	                                             .log("fork");

	forkStream.subscribe(computationEmitterProcessor);
	forkStream.subscribe(persistenceEmitterProcessor);

	final Flux<List<String>> joinStream = Flux.zip(computationStream, persistenceStream, (a, b) -> Arrays.asList(a, b))
	                                                .publishOn(forkJoin)
	                                                .map(listOfLists -> {
		                                               listOfLists.get(0)
		                                                          .addAll(listOfLists.get(1));
		                                               return listOfLists.get(0);
	                                               })
	                                                .log("join");

	final Semaphore doneSemaphore = new Semaphore(0);

	final MonoProcessor<List<String>> listPromise = joinStream.flatMap(Flux::fromIterable)
	                                                 .log("resultStream")
	                                                 .collectList()
	                                                 .doOnTerminate(doneSemaphore::release)
	                                                 .toProcessor();
	listPromise.subscribe();

	forkEmitterProcessor.onNext(1);
	forkEmitterProcessor.onNext(2);
	forkEmitterProcessor.onNext(3);
	forkEmitterProcessor.onComplete();

	List<String> res = listPromise.block(Duration.ofSeconds(5));
	assertEquals(Arrays.asList("i0", "done1", "i0", "i1", "done2", "i0", "i1", "i2", "done3"), res);

	forkJoin.dispose();
	persistence.dispose();
	computation.dispose();
}