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

The following examples show how to use reactor.core.publisher.MonoProcessor#onNext() . 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: RSocketPayloadReturnValueHandler.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected Mono<Void> handleEncodedContent(
		Flux<DataBuffer> encodedContent, MethodParameter returnType, Message<?> message) {

	MonoProcessor<Flux<Payload>> replyMono = getReplyMono(message);
	Assert.notNull(replyMono, "Missing '" + RESPONSE_HEADER + "'");
	replyMono.onNext(encodedContent.map(PayloadUtils::createPayload));
	replyMono.onComplete();
	return Mono.empty();
}
 
Example 3
Source File: ErrorsMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void resolveWithMono() {
	BindingResult bindingResult = createBindingResult(new Foo(), "foo");
	MonoProcessor<BindingResult> monoProcessor = MonoProcessor.create();
	monoProcessor.onNext(bindingResult);
	this.bindingContext.getModel().asMap().put(BindingResult.MODEL_KEY_PREFIX + "foo", monoProcessor);

	MethodParameter parameter = this.testMethod.arg(Errors.class);
	Object actual = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
			.block(Duration.ofMillis(5000));

	assertSame(bindingResult, actual);
}
 
Example 4
Source File: ErrorsMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void resolveWithMono() {
	BindingResult bindingResult = createBindingResult(new Foo(), "foo");
	MonoProcessor<BindingResult> monoProcessor = MonoProcessor.create();
	monoProcessor.onNext(bindingResult);
	this.bindingContext.getModel().asMap().put(BindingResult.MODEL_KEY_PREFIX + "foo", monoProcessor);

	MethodParameter parameter = this.testMethod.arg(Errors.class);
	Object actual = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange)
			.block(Duration.ofMillis(5000));

	assertSame(bindingResult, actual);
}
 
Example 5
Source File: MonoTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testMono() throws Exception {
	MonoProcessor<String> promise = MonoProcessor.create();
	promise.onNext("test");
	final CountDownLatch successCountDownLatch = new CountDownLatch(1);
	promise.subscribe(v -> successCountDownLatch.countDown());
	assertThat("Failed", successCountDownLatch.await(10, TimeUnit.SECONDS));
}
 
Example 6
Source File: FluxTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void promiseAcceptCountCannotExceedOne() {
	MonoProcessor<Object> deferred = MonoProcessor.create();
	deferred.onNext("alpha");
	try {
		deferred.onNext("bravo");
	}
	catch (Exception e) {
		if(!Exceptions.isCancel(e)) {
			throw e;
		}
	}
	assertEquals(deferred.block(), "alpha");
}
 
Example 7
Source File: ResolvingOperatorTests.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldExpireValueOnRacingDisposeAndComplete() {
  for (int i = 0; i < 10000; i++) {
    final int index = i;

    MonoProcessor<String> processor = MonoProcessor.create();
    BiConsumer<String, Throwable> consumer =
        (v, t) -> {
          if (t != null) {
            processor.onError(t);
            return;
          }

          processor.onNext(v);
        };

    ResolvingTest.<String>create()
        .assertNothingExpired()
        .assertNothingReceived()
        .assertPendingResolution()
        .thenAddObserver(consumer)
        .assertPendingSubscribers(1)
        .assertPendingResolution()
        .then(self -> RaceTestUtils.race(() -> self.complete("value" + index), self::dispose))
        .assertDisposeCalled(1)
        .assertExpiredExactly("value" + index)
        .ifResolvedAssertEqual("value" + index)
        .assertIsDisposed();

    if (processor.isError()) {
      Assertions.assertThat(processor.getError())
          .isInstanceOf(CancellationException.class)
          .hasMessage("Disposed");

    } else {
      Assertions.assertThat(processor.peek()).isEqualTo("value" + i);
    }
  }
}
 
Example 8
Source File: ClientLogicTest.java    From sample-webflux-websocket-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void testStart() throws Exception
{
	URI uri = new URI("http://127.0.0.1");
	
	MonoProcessor<WebSocketSession> connectedProcessor = MonoProcessor.create();
	MonoProcessor<WebSocketSession> disconnectedProcessor = MonoProcessor.create();
	
	Mockito
		.when(webSocketClient.execute(Mockito.eq(uri), Mockito.any()))
		.thenReturn(Mono.empty());		
	
	Mockito
		.when(clientWebSocketHandler.connected())
		.thenReturn(Mono.just(sessionHandler).flux());
	
	Mockito
		.when(sessionHandler.connected())
		.thenReturn(connectedProcessor);
	
	Mockito
		.when(sessionHandler.disconnected())
		.thenReturn(disconnectedProcessor);
	
	Mockito
		.when(sessionHandler.receive())
		.thenReturn(Flux.fromArray(new String[] {"A", "B", "C"}).cache());		
	
	ClientLogic clientLogic = new ClientLogic();
	clientLogic.start(webSocketClient, uri, clientWebSocketHandler);			
	
	connectedProcessor.onNext(session);
	disconnectedProcessor.onNext(session);
	
	Mono
		.delay(Duration.ofMillis(50))
		.block();
	
	Mockito
		.verify(sessionHandler, Mockito.times(1))
		.connected();
	
	Mockito
		.verify(sessionHandler, Mockito.times(1))
		.disconnected();
	
	Mockito
		.verify(sessionHandler, Mockito.atLeast(1))
		.receive();
	
	Mockito
		.verify(sessionHandler, Mockito.times(1))
		.send(Mockito.anyString());		
}
 
Example 9
Source File: ServerLogicTest.java    From sample-webflux-websocket-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void testStart()
{
	MonoProcessor<WebSocketSession> connectedProcessor = MonoProcessor.create();
	MonoProcessor<WebSocketSession> disconnectedProcessor = MonoProcessor.create();
	
	Mockito
		.when(serverWebSocketHandler.connected())
		.thenReturn(Mono.just(sessionHandler).flux());
	
	Mockito
		.when(sessionHandler.connected())
		.thenReturn(connectedProcessor);
	
	Mockito
		.when(sessionHandler.disconnected())
		.thenReturn(disconnectedProcessor);
	
	Mockito
		.when(sessionHandler.receive())
		.thenReturn(Flux.fromArray(new String[] {"A", "B", "C"}).cache());
	
	ServerLogic serverLogic = new ServerLogic();
	serverLogic.start(serverWebSocketHandler, 25);
	
	connectedProcessor.onNext(session);
	disconnectedProcessor.onNext(session);
	
	Mono
		.delay(Duration.ofMillis(50))
		.block();
	
	Mockito
		.verify(sessionHandler, Mockito.times(1))
		.connected();
	
	Mockito
		.verify(sessionHandler, Mockito.times(1))
		.disconnected();
	
	Mockito
		.verify(sessionHandler, Mockito.atLeast(1))
		.receive();
	
	Mockito
		.verify(sessionHandler, Mockito.atLeast(1))
		.send(Mockito.anyString());
}
 
Example 10
Source File: ResolvingOperatorTests.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldNotifyAllTheSubscribersUnderRacingBetweenSubscribeAndComplete() {
  for (int i = 0; i < 10000; i++) {
    final String valueToSend = "value" + i;

    MonoProcessor<String> processor = MonoProcessor.create();
    BiConsumer<String, Throwable> consumer =
        (v, t) -> {
          if (t != null) {
            processor.onError(t);
            return;
          }

          processor.onNext(v);
        };

    MonoProcessor<String> processor2 = MonoProcessor.create();
    BiConsumer<String, Throwable> consumer2 =
        (v, t) -> {
          if (t != null) {
            processor2.onError(t);
            return;
          }

          processor2.onNext(v);
        };

    ResolvingTest.<String>create()
        .assertNothingExpired()
        .assertNothingReceived()
        .assertPendingSubscribers(0)
        .assertPendingResolution()
        .then(
            self -> {
              RaceTestUtils.race(() -> self.complete(valueToSend), () -> self.observe(consumer));

              StepVerifier.create(processor)
                  .expectNext(valueToSend)
                  .expectComplete()
                  .verify(Duration.ofMillis(10));
            })
        .assertDisposeCalled(0)
        .assertReceivedExactly(valueToSend)
        .assertNothingExpired()
        .thenAddObserver(consumer2)
        .assertPendingSubscribers(0);

    StepVerifier.create(processor2)
        .expectNext(valueToSend)
        .expectComplete()
        .verify(Duration.ofMillis(10));
  }
}
 
Example 11
Source File: ResolvingOperatorTests.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldNotExpireNewlyResolvedValueIfSubscribeIsRacingWithInvalidate() {
  for (int i = 0; i < 10000; i++) {
    final String valueToSend = "value" + i;
    final String valueToSend2 = "value2" + i;

    MonoProcessor<String> processor = MonoProcessor.create();
    BiConsumer<String, Throwable> consumer =
        (v, t) -> {
          if (t != null) {
            processor.onError(t);
            return;
          }

          processor.onNext(v);
        };

    MonoProcessor<String> processor2 = MonoProcessor.create();
    BiConsumer<String, Throwable> consumer2 =
        (v, t) -> {
          if (t != null) {
            processor2.onError(t);
            return;
          }

          processor2.onNext(v);
        };

    ResolvingTest.<String>create()
        .assertNothingExpired()
        .assertNothingReceived()
        .assertPendingSubscribers(0)
        .assertPendingResolution()
        .thenAddObserver(consumer)
        .then(
            self -> {
              self.complete(valueToSend);

              StepVerifier.create(processor)
                  .expectNext(valueToSend)
                  .expectComplete()
                  .verify(Duration.ofMillis(10));
            })
        .assertReceivedExactly(valueToSend)
        .then(
            self ->
                RaceTestUtils.race(
                    self::invalidate,
                    () -> {
                      self.observe(consumer2);
                      if (!processor2.isTerminated()) {
                        self.complete(valueToSend2);
                      }
                    },
                    Schedulers.parallel()))
        .then(
            self -> {
              if (self.isPending()) {
                self.assertReceivedExactly(valueToSend);
              } else {
                self.assertReceivedExactly(valueToSend, valueToSend2);
              }
            })
        .assertExpiredExactly(valueToSend)
        .assertPendingSubscribers(0)
        .assertDisposeCalled(0)
        .then(
            self ->
                StepVerifier.create(processor2)
                    .expectNextMatches(
                        (v) -> {
                          if (self.subscribers == ResolvingOperator.READY) {
                            return v.equals(valueToSend2);
                          } else {
                            return v.equals(valueToSend);
                          }
                        })
                    .expectComplete()
                    .verify(Duration.ofMillis(100)));
  }
}
 
Example 12
Source File: ResolvingOperatorTests.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldNotExpireNewlyResolvedValueIfBlockIsRacingWithInvalidate() {
  for (int i = 0; i < 10000; i++) {
    final String valueToSend = "value" + i;
    final String valueToSend2 = "value2" + i;

    MonoProcessor<String> processor = MonoProcessor.create();
    BiConsumer<String, Throwable> consumer =
        (v, t) -> {
          if (t != null) {
            processor.onError(t);
            return;
          }

          processor.onNext(v);
        };

    ResolvingTest.<String>create()
        .assertNothingExpired()
        .assertNothingReceived()
        .assertPendingSubscribers(0)
        .assertPendingResolution()
        .thenAddObserver(consumer)
        .then(
            self -> {
              self.complete(valueToSend);

              StepVerifier.create(processor)
                  .expectNext(valueToSend)
                  .expectComplete()
                  .verify(Duration.ofMillis(10));
            })
        .assertReceivedExactly(valueToSend)
        .then(
            self ->
                RaceTestUtils.race(
                    () ->
                        Assertions.assertThat(self.block(null))
                            .matches((v) -> v.equals(valueToSend) || v.equals(valueToSend2)),
                    () ->
                        RaceTestUtils.race(
                            self::invalidate,
                            () -> {
                              for (; ; ) {
                                if (self.subscribers != ResolvingOperator.READY) {
                                  self.complete(valueToSend2);
                                  break;
                                }
                              }
                            },
                            Schedulers.parallel()),
                    Schedulers.parallel()))
        .then(
            self -> {
              if (self.isPending()) {
                self.assertReceivedExactly(valueToSend);
              } else {
                self.assertReceivedExactly(valueToSend, valueToSend2);
              }
            })
        .assertExpiredExactly(valueToSend)
        .assertPendingSubscribers(0)
        .assertDisposeCalled(0);
  }
}
 
Example 13
Source File: ResolvingOperatorTests.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldEstablishValueOnceInCaseOfRacingBetweenSubscribers() {
  for (int i = 0; i < 10000; i++) {
    final String valueToSend = "value" + i;

    MonoProcessor<String> processor = MonoProcessor.create();
    BiConsumer<String, Throwable> consumer =
        (v, t) -> {
          if (t != null) {
            processor.onError(t);
            return;
          }

          processor.onNext(v);
        };

    MonoProcessor<String> processor2 = MonoProcessor.create();
    BiConsumer<String, Throwable> consumer2 =
        (v, t) -> {
          if (t != null) {
            processor2.onError(t);
            return;
          }

          processor2.onNext(v);
        };

    ResolvingTest.<String>create()
        .assertNothingExpired()
        .assertNothingReceived()
        .assertPendingSubscribers(0)
        .assertPendingResolution()
        .then(
            self ->
                RaceTestUtils.race(() -> self.observe(consumer), () -> self.observe(consumer2)))
        .assertSubscribeCalled(1)
        .assertPendingSubscribers(2)
        .then(self -> self.complete(valueToSend))
        .assertPendingSubscribers(0)
        .assertReceivedExactly(valueToSend)
        .assertNothingExpired()
        .assertDisposeCalled(0)
        .then(
            self -> {
              Assertions.assertThat(processor.isTerminated()).isTrue();
              Assertions.assertThat(processor2.isTerminated()).isTrue();

              Assertions.assertThat(processor.peek()).isEqualTo(valueToSend);
              Assertions.assertThat(processor2.peek()).isEqualTo(valueToSend);

              Assertions.assertThat(self.subscribers).isEqualTo(ResolvingOperator.READY);

              Assertions.assertThat(self.add(consumer)).isEqualTo(ResolvingOperator.READY_STATE);
            });
  }
}
 
Example 14
Source File: ResolvingOperatorTests.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldEstablishValueOnceInCaseOfRacingBetweenSubscribeAndBlock() {
  for (int i = 0; i < 10000; i++) {
    final String valueToSend = "value" + i;

    MonoProcessor<String> processor = MonoProcessor.create();

    MonoProcessor<String> processor2 = MonoProcessor.create();
    BiConsumer<String, Throwable> consumer2 =
        (v, t) -> {
          if (t != null) {
            processor2.onError(t);
            return;
          }

          processor2.onNext(v);
        };

    ResolvingTest.<String>create()
        .assertNothingExpired()
        .assertNothingReceived()
        .assertPendingSubscribers(0)
        .assertPendingResolution()
        .whenSubscribe(self -> self.complete(valueToSend))
        .then(
            self ->
                RaceTestUtils.race(
                    () -> processor.onNext(self.block(null)), () -> self.observe(consumer2)))
        .assertSubscribeCalled(1)
        .assertPendingSubscribers(0)
        .assertReceivedExactly(valueToSend)
        .assertNothingExpired()
        .assertDisposeCalled(0)
        .then(
            self -> {
              Assertions.assertThat(processor.isTerminated()).isTrue();
              Assertions.assertThat(processor2.isTerminated()).isTrue();

              Assertions.assertThat(processor.peek()).isEqualTo(valueToSend);
              Assertions.assertThat(processor2.peek()).isEqualTo(valueToSend);

              Assertions.assertThat(self.subscribers).isEqualTo(ResolvingOperator.READY);

              Assertions.assertThat(self.add(consumer2)).isEqualTo(ResolvingOperator.READY_STATE);
            });
  }
}
 
Example 15
Source File: ResolvingOperatorTests.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldExpireValueOnRacingDisposeAndError() {
  Hooks.onErrorDropped(t -> {});
  RuntimeException runtimeException = new RuntimeException("test");
  for (int i = 0; i < 10000; i++) {
    MonoProcessor<String> processor = MonoProcessor.create();
    BiConsumer<String, Throwable> consumer =
        (v, t) -> {
          if (t != null) {
            processor.onError(t);
            return;
          }

          processor.onNext(v);
        };
    MonoProcessor<String> processor2 = MonoProcessor.create();
    BiConsumer<String, Throwable> consumer2 =
        (v, t) -> {
          if (t != null) {
            processor2.onError(t);
            return;
          }

          processor2.onNext(v);
        };

    ResolvingTest.<String>create()
        .assertNothingExpired()
        .assertNothingReceived()
        .assertPendingSubscribers(0)
        .assertPendingResolution()
        .thenAddObserver(consumer)
        .assertSubscribeCalled(1)
        .assertPendingSubscribers(1)
        .then(self -> RaceTestUtils.race(() -> self.terminate(runtimeException), self::dispose))
        .assertPendingSubscribers(0)
        .assertNothingExpired()
        .assertDisposeCalled(1)
        .then(
            self -> {
              Assertions.assertThat(self.subscribers).isEqualTo(ResolvingOperator.TERMINATED);

              Assertions.assertThat(self.add((v, t) -> {}))
                  .isEqualTo(ResolvingOperator.TERMINATED_STATE);
            })
        .thenAddObserver(consumer2);

    StepVerifier.create(processor)
        .expectErrorSatisfies(
            t -> {
              if (t instanceof CancellationException) {
                Assertions.assertThat(t)
                    .isInstanceOf(CancellationException.class)
                    .hasMessage("Disposed");
              } else {
                Assertions.assertThat(t).isInstanceOf(RuntimeException.class).hasMessage("test");
              }
            })
        .verify(Duration.ofMillis(10));

    StepVerifier.create(processor2)
        .expectErrorSatisfies(
            t -> {
              if (t instanceof CancellationException) {
                Assertions.assertThat(t)
                    .isInstanceOf(CancellationException.class)
                    .hasMessage("Disposed");
              } else {
                Assertions.assertThat(t).isInstanceOf(RuntimeException.class).hasMessage("test");
              }
            })
        .verify(Duration.ofMillis(10));

    // no way to guarantee equality because of racing
    //      Assertions.assertThat(processor.getError())
    //                .isEqualTo(processor2.getError());
  }
}