reactor.core.publisher.MonoProcessor Java Examples

The following examples show how to use reactor.core.publisher.MonoProcessor. 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: ReactorNettyTcpClient.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public ListenableFuture<Void> connect(TcpConnectionHandler<P> handler, ReconnectStrategy strategy) {
	Assert.notNull(handler, "TcpConnectionHandler is required");
	Assert.notNull(strategy, "ReconnectStrategy is required");

	if (this.stopping) {
		return handleShuttingDownConnectFailure(handler);
	}

	// Report first connect to the ListenableFuture
	MonoProcessor<Void> connectMono = MonoProcessor.create();

	this.tcpClient
			.handle(new ReactorNettyHandler(handler))
			.connect()
			.doOnNext(updateConnectMono(connectMono))
			.doOnError(updateConnectMono(connectMono))
			.doOnError(handler::afterConnectFailure)    // report all connect failures to the handler
			.flatMap(Connection::onDispose)             // post-connect issues
			.retryWhen(reconnectFunction(strategy))
			.repeatWhen(reconnectFunction(strategy))
			.subscribe();

	return new MonoToListenableFutureAdapter<>(connectMono);
}
 
Example #2
Source File: RSocketSupplierPool.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
public RSocketSupplierPool(Publisher<? extends Collection<RSocketSupplier>> publisher) {
  this.onClose = MonoProcessor.create();
  this.factoryPool = new ArrayList<>();
  this.leasedSuppliers = new ArrayList<>();

  Disposable disposable =
      Flux.from(publisher)
          .doOnNext(this::handleNewFactories)
          .onErrorResume(
              t -> {
                logger.error("error streaming RSocketSuppliers", t);
                return Mono.delay(Duration.ofSeconds(10)).then(Mono.error(t));
              })
          .subscribe();

  onClose.doFinally(s -> disposable.dispose()).subscribe();
}
 
Example #3
Source File: StandardWebSocketClient.java    From java-technology-stack with MIT License 6 votes vote down vote up
private Mono<Void> executeInternal(URI url, HttpHeaders requestHeaders, WebSocketHandler handler) {
	MonoProcessor<Void> completionMono = MonoProcessor.create();
	return Mono.fromCallable(
			() -> {
				if (logger.isDebugEnabled()) {
					logger.debug("Connecting to " + url);
				}
				List<String> protocols = handler.getSubProtocols();
				DefaultConfigurator configurator = new DefaultConfigurator(requestHeaders);
				Endpoint endpoint = createEndpoint(url, handler, completionMono, configurator);
				ClientEndpointConfig config = createEndpointConfig(configurator, protocols);
				return this.webSocketContainer.connectToServer(endpoint, config, url);
			})
			.subscribeOn(Schedulers.elastic()) // connectToServer is blocking
			.then(completionMono);
}
 
Example #4
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 #5
Source File: FluxTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void promiseErrorCountCannotExceedOne() {
	MonoProcessor<Object> deferred = MonoProcessor.create();
	Throwable error = new IOException("foo");

	StepVerifier.create(deferred)
	            .then(() -> {
		            deferred.onError(error);
		            deferred.onNext(error);
	            })
	            .expectErrorMessage("foo")
	            .verifyThenAssertThat()
	            .hasDroppedExactly(error);

	Assertions.assertThat(deferred.getError()).isSameAs(error);
}
 
Example #6
Source File: FluxSpecTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
	public void reduceWillAccumulateListOfAcceptedValues() {
//		"Reduce will accumulate a list of accepted values"
//		given: "a composable"
		FluxIdentityProcessor<Integer> source =
				Processors.multicast();
		Mono<List<Integer>> reduced = source.collectList();
		MonoProcessor<List<Integer>> value = reduced.toProcessor();
		value.subscribe();

//		when: "the first value is accepted"
		source.onNext(1);
		source.onComplete();

//		then: "the list contains the first element"
		assertThat(value.block()).containsExactly(1);
	}
 
Example #7
Source File: ReactiveTypeHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void deferredResultSubscriberWithOneValue() throws Exception {

	// Mono
	MonoProcessor<String> mono = MonoProcessor.create();
	testDeferredResultSubscriber(mono, Mono.class, forClass(String.class), () -> mono.onNext("foo"), "foo");

	// Mono empty
	MonoProcessor<String> monoEmpty = MonoProcessor.create();
	testDeferredResultSubscriber(monoEmpty, Mono.class, forClass(String.class), monoEmpty::onComplete, null);

	// RxJava 1 Single
	AtomicReference<SingleEmitter<String>> ref = new AtomicReference<>();
	Single<String> single = Single.fromEmitter(ref::set);
	testDeferredResultSubscriber(single, Single.class, forClass(String.class),
			() -> ref.get().onSuccess("foo"), "foo");

	// RxJava 2 Single
	AtomicReference<io.reactivex.SingleEmitter<String>> ref2 = new AtomicReference<>();
	io.reactivex.Single<String> single2 = io.reactivex.Single.create(ref2::set);
	testDeferredResultSubscriber(single2, io.reactivex.Single.class, forClass(String.class),
			() -> ref2.get().onSuccess("foo"), "foo");
}
 
Example #8
Source File: SyncInvocableHandlerMethod.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Invoke the method for the given exchange.
 * @param exchange the current exchange
 * @param bindingContext the binding context to use
 * @param providedArgs optional list of argument values to match by type
 * @return a Mono with a {@link HandlerResult}.
 * @throws ServerErrorException if method argument resolution or method invocation fails
 */
@Nullable
public HandlerResult invokeForHandlerResult(ServerWebExchange exchange,
		BindingContext bindingContext, Object... providedArgs) {

	MonoProcessor<HandlerResult> processor = MonoProcessor.create();
	this.delegate.invoke(exchange, bindingContext, providedArgs).subscribeWith(processor);

	if (processor.isTerminated()) {
		Throwable ex = processor.getError();
		if (ex != null) {
			throw (ex instanceof ServerErrorException ? (ServerErrorException) ex :
					new ServerErrorException("Failed to invoke: " + getShortLogMessage(), getMethod(), ex));
		}
		return processor.peek();
	}
	else {
		// Should never happen...
		throw new IllegalStateException(
				"SyncInvocableHandlerMethod should have completed synchronously.");
	}
}
 
Example #9
Source File: FluxSpecTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
	public void streamCanBeCounted() {
//		"Stream can be counted"
//		given: "source composables to count and tap"
		FluxIdentityProcessor<Integer> source = Processors.multicast();
		MonoProcessor<Long> tap = source.count()
		                                .subscribeWith(MonoProcessor.create());

//		when: "the sources accept a value"
		source.onNext(1);
		source.onNext(2);
		source.onNext(3);
		source.onComplete();

//		then: "the count value matches the number of accept"
		assertThat(tap.peek()).isEqualTo(3);
	}
 
Example #10
Source File: ReactiveTypeHandlerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void deferredResultSubscriberWithError() throws Exception {

	IllegalStateException ex = new IllegalStateException();

	// Mono
	MonoProcessor<String> mono = MonoProcessor.create();
	testDeferredResultSubscriber(mono, Mono.class, forClass(String.class), () -> mono.onError(ex), ex);

	// RxJava 1 Single
	AtomicReference<SingleEmitter<String>> ref = new AtomicReference<>();
	Single<String> single = Single.fromEmitter(ref::set);
	testDeferredResultSubscriber(single, Single.class, forClass(String.class), () -> ref.get().onError(ex), ex);

	// RxJava 2 Single
	AtomicReference<io.reactivex.SingleEmitter<String>> ref2 = new AtomicReference<>();
	io.reactivex.Single<String> single2 = io.reactivex.Single.create(ref2::set);
	testDeferredResultSubscriber(single2, io.reactivex.Single.class, forClass(String.class),
			() -> ref2.get().onError(ex), ex);
}
 
Example #11
Source File: LocalClientTransport.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<DuplexConnection> connect() {
  return Mono.defer(
      () -> {
        ServerTransport.ConnectionAcceptor server = LocalServerTransport.findServer(name);
        if (server == null) {
          return Mono.error(new IllegalArgumentException("Could not find server: " + name));
        }

        UnboundedProcessor<ByteBuf> in = new UnboundedProcessor<>();
        UnboundedProcessor<ByteBuf> out = new UnboundedProcessor<>();
        MonoProcessor<Void> closeNotifier = MonoProcessor.create();

        server.apply(new LocalDuplexConnection(allocator, out, in, closeNotifier)).subscribe();

        return Mono.just(
            (DuplexConnection) new LocalDuplexConnection(allocator, in, out, closeNotifier));
      });
}
 
Example #12
Source File: ReactiveTypeHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void deferredResultSubscriberWithOneValue() throws Exception {

	// Mono
	MonoProcessor<String> mono = MonoProcessor.create();
	testDeferredResultSubscriber(mono, Mono.class, forClass(String.class), () -> mono.onNext("foo"), "foo");

	// Mono empty
	MonoProcessor<String> monoEmpty = MonoProcessor.create();
	testDeferredResultSubscriber(monoEmpty, Mono.class, forClass(String.class), monoEmpty::onComplete, null);

	// RxJava 1 Single
	AtomicReference<SingleEmitter<String>> ref = new AtomicReference<>();
	Single<String> single = Single.fromEmitter(ref::set);
	testDeferredResultSubscriber(single, Single.class, forClass(String.class),
			() -> ref.get().onSuccess("foo"), "foo");

	// RxJava 2 Single
	AtomicReference<io.reactivex.SingleEmitter<String>> ref2 = new AtomicReference<>();
	io.reactivex.Single<String> single2 = io.reactivex.Single.create(ref2::set);
	testDeferredResultSubscriber(single2, io.reactivex.Single.class, forClass(String.class),
			() -> ref2.get().onSuccess("foo"), "foo");
}
 
Example #13
Source File: ReactiveTypeHandlerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void deferredResultSubscriberWithError() throws Exception {

	IllegalStateException ex = new IllegalStateException();

	// Mono
	MonoProcessor<String> mono = MonoProcessor.create();
	testDeferredResultSubscriber(mono, Mono.class, forClass(String.class), () -> mono.onError(ex), ex);

	// RxJava 1 Single
	AtomicReference<SingleEmitter<String>> ref = new AtomicReference<>();
	Single<String> single = Single.fromEmitter(ref::set);
	testDeferredResultSubscriber(single, Single.class, forClass(String.class), () -> ref.get().onError(ex), ex);

	// RxJava 2 Single
	AtomicReference<io.reactivex.SingleEmitter<String>> ref2 = new AtomicReference<>();
	io.reactivex.Single<String> single2 = io.reactivex.Single.create(ref2::set);
	testDeferredResultSubscriber(single2, io.reactivex.Single.class, forClass(String.class),
			() -> ref2.get().onError(ex), ex);
}
 
Example #14
Source File: FluxSpecTests.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
	public void knownNumberOfValuesCanBeReduced() {
//		"A known number of values can be reduced"
//		given: "a composable that will accept 5 values and a reduce function"
		FluxIdentityProcessor<Integer> source = Processors.multicast();
		Mono<Integer> reduced = source.reduce(new Reduction());
		MonoProcessor<Integer> value = reduced.subscribeWith(MonoProcessor.create());

//		when: "the expected number of values is accepted"
		source.onNext(1);
		source.onNext(2);
		source.onNext(3);
		source.onNext(4);
		source.onNext(5);
		source.onComplete();

//		then: "the reduced composable holds the reduced value"
		assertThat(value.peek()).isEqualTo(120);
	}
 
Example #15
Source File: HeaderAssertionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private HeaderAssertions headerAssertions(HttpHeaders responseHeaders) {
	MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create("/"));
	MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK);
	response.getHeaders().putAll(responseHeaders);

	MonoProcessor<byte[]> emptyContent = MonoProcessor.create();
	emptyContent.onComplete();

	ExchangeResult result = new ExchangeResult(request, response, emptyContent, emptyContent, Duration.ZERO, null);
	return new HeaderAssertions(result, mock(WebTestClient.ResponseSpec.class));
}
 
Example #16
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 #17
Source File: JettyWebSocketSession.java    From java-technology-stack with MIT License 5 votes vote down vote up
public JettyWebSocketSession(Session session, HandshakeInfo info, DataBufferFactory factory,
		@Nullable MonoProcessor<Void> completionMono) {

	super(session, ObjectUtils.getIdentityHexString(session), info, factory, completionMono);
	// TODO: suspend causes failures if invoked at this stage
	// suspendReceiving();
}
 
Example #18
Source File: WebSocketIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void customHeader() throws Exception {
	HttpHeaders headers = new HttpHeaders();
	headers.add("my-header", "my-value");
	MonoProcessor<Object> output = MonoProcessor.create();

	this.client.execute(getUrl("/custom-header"), headers,
			session -> session.receive()
					.map(WebSocketMessage::getPayloadAsText)
					.subscribeWith(output)
					.then())
			.block(TIMEOUT);

	assertEquals("my-header:my-value", output.block(TIMEOUT));
}
 
Example #19
Source File: WebSocketIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void subProtocol() throws Exception {
	String protocol = "echo-v1";
	AtomicReference<HandshakeInfo> infoRef = new AtomicReference<>();
	MonoProcessor<Object> output = MonoProcessor.create();

	this.client.execute(getUrl("/sub-protocol"),
			new WebSocketHandler() {
				@Override
				public List<String> getSubProtocols() {
					return Collections.singletonList(protocol);
				}
				@Override
				public Mono<Void> handle(WebSocketSession session) {
					infoRef.set(session.getHandshakeInfo());
					return session.receive()
							.map(WebSocketMessage::getPayloadAsText)
							.subscribeWith(output)
							.then();
				}
			})
			.block(TIMEOUT);

	HandshakeInfo info = infoRef.get();
	assertThat(info.getHeaders().getFirst("Upgrade"), Matchers.equalToIgnoringCase("websocket"));
	assertEquals(protocol, info.getHeaders().getFirst("Sec-WebSocket-Protocol"));
	assertEquals("Wrong protocol accepted", protocol, info.getSubProtocol());
	assertEquals("Wrong protocol detected on the server side", protocol, output.block(TIMEOUT));
}
 
Example #20
Source File: MockServerHttpResponse.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public MockServerHttpResponse(DataBufferFactory dataBufferFactory) {
	super(dataBufferFactory);
	this.writeHandler = body -> {
		// Avoid .then() which causes data buffers to be released
		MonoProcessor<Void> completion = MonoProcessor.create();
		this.body = body.doOnComplete(completion::onComplete).doOnError(completion::onError).cache();
		this.body.subscribe();
		return completion;
	};
}
 
Example #21
Source File: WebSocketSessionHandler.java    From sample-webflux-websocket-netty with Apache License 2.0 5 votes vote down vote up
public WebSocketSessionHandler(int historySize)
{
	receiveProcessor = ReplayProcessor.create(historySize);
	connectedProcessor = MonoProcessor.create();
	disconnectedProcessor = MonoProcessor.create();
	
	webSocketConnected = false;
}
 
Example #22
Source File: UndertowWebSocketClient.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void handleChannel(URI url, WebSocketHandler handler, MonoProcessor<Void> completion,
		DefaultNegotiation negotiation, WebSocketChannel channel) {

	HandshakeInfo info = createHandshakeInfo(url, negotiation);
	UndertowWebSocketSession session = new UndertowWebSocketSession(channel, info, this.bufferFactory, completion);
	UndertowWebSocketHandlerAdapter adapter = new UndertowWebSocketHandlerAdapter(session);

	channel.getReceiveSetter().set(adapter);
	channel.resumeReceives();

	handler.handle(session).subscribe(session);
}
 
Example #23
Source File: EventDispatcher.java    From james-project with Apache License 2.0 5 votes vote down vote up
Mono<Void> dispatch(Event event, Set<RegistrationKey> keys) {
    return Flux
        .concat(
            dispatchToLocalListeners(event, keys),
            dispatchToRemoteListeners(event, keys))
        .doOnError(throwable -> LOGGER.error("error while dispatching event", throwable))
        .then()
        .subscribeWith(MonoProcessor.create());
}
 
Example #24
Source File: StatusAssertionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private StatusAssertions statusAssertions(HttpStatus status) {
	MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create("/"));
	MockClientHttpResponse response = new MockClientHttpResponse(status);

	MonoProcessor<byte[]> emptyContent = MonoProcessor.create();
	emptyContent.onComplete();

	ExchangeResult result = new ExchangeResult(request, response, emptyContent, emptyContent, Duration.ZERO, null);
	return new StatusAssertions(result, mock(WebTestClient.ResponseSpec.class));
}
 
Example #25
Source File: JettyWebSocketClient.java    From java-technology-stack with MIT License 5 votes vote down vote up
private Mono<Void> executeInternal(URI url, HttpHeaders headers, WebSocketHandler handler) {
	MonoProcessor<Void> completionMono = MonoProcessor.create();
	return Mono.fromCallable(
			() -> {
				if (logger.isDebugEnabled()) {
					logger.debug("Connecting to " + url);
				}
				Object jettyHandler = createHandler(url, handler, completionMono);
				ClientUpgradeRequest request = new ClientUpgradeRequest();
				request.setSubProtocols(handler.getSubProtocols());
				UpgradeListener upgradeListener = new DefaultUpgradeListener(headers);
				return this.jettyClient.connect(jettyHandler, url, request, upgradeListener);
			})
			.then(completionMono);
}
 
Example #26
Source File: DefaultRSocketClientTests.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Override
protected void init() {
  super.init();
  delayer = () -> producer.onNext(socket);
  producer = MonoProcessor.create();
  client =
      new DefaultRSocketClient(
          producer
              .doOnCancel(() -> socket.dispose())
              .doOnDiscard(Disposable.class, Disposable::dispose));
}
 
Example #27
Source File: ReconnectMonoTests.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldExpireValueOnRacingDisposeAndNoValueComplete() {
  Hooks.onErrorDropped(t -> {});
  for (int i = 0; i < 10000; i++) {
    final TestPublisher<String> cold =
        TestPublisher.createNoncompliant(TestPublisher.Violation.REQUEST_OVERFLOW);

    final ReconnectMono<String> reconnectMono =
        cold.mono().as(source -> new ReconnectMono<>(source, onExpire(), onValue()));

    final MonoProcessor<String> processor = reconnectMono.subscribeWith(MonoProcessor.create());

    Assertions.assertThat(expired).isEmpty();
    Assertions.assertThat(received).isEmpty();

    RaceTestUtils.race(cold::complete, reconnectMono::dispose);

    Assertions.assertThat(processor.isTerminated()).isTrue();

    Throwable error = processor.getError();

    if (error instanceof CancellationException) {
      Assertions.assertThat(error)
          .isInstanceOf(CancellationException.class)
          .hasMessage("ReconnectMono has already been disposed");
    } else {
      Assertions.assertThat(error)
          .isInstanceOf(IllegalStateException.class)
          .hasMessage("Source completed empty");
    }

    Assertions.assertThat(expired).isEmpty();

    expired.clear();
    received.clear();
  }
}
 
Example #28
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testNormalConnectionCloseForWebSocketServer() {
	MonoProcessor<WebSocketCloseStatus> statusServer = MonoProcessor.create();
	MonoProcessor<WebSocketCloseStatus> statusClient = MonoProcessor.create();

	disposableServer = HttpServer.create()
	                             .port(0)
	                             .handle((req, resp) ->
	                                 resp.sendWebsocket((in, out) -> in.receiveCloseStatus()
	                                                                   .subscribeWith(statusServer)
	                                                                   .then()))
	                             .wiretap(true)
	                             .bindNow();

	HttpClient.create()
	          .port(disposableServer.port())
	          .wiretap(true)
	          .websocket()
	          .uri("/")
	          .handle((in, out) -> out.sendClose(4404, "test")
	                                  .then(in.receiveCloseStatus()
	                                          .subscribeWith(statusClient)))
	          .blockLast();

	StepVerifier.create(statusClient)
	            .expectNext(new WebSocketCloseStatus(4404, "test"))
	            .expectComplete()
	            .verify(Duration.ofSeconds(30));

	StepVerifier.create(statusServer)
	            .expectNext(new WebSocketCloseStatus(4404, "test"))
	            .expectComplete()
	            .verify(Duration.ofSeconds(30));
}
 
Example #29
Source File: TestServer.java    From spring-graalvm-native with Apache License 2.0 5 votes vote down vote up
@Bean
public Function<String, String> add() {
    return input -> {
        System.err.println("Add: " + input);
        output.onNext(input);
        output = MonoProcessor.<String>create();
        return "Added: " + input;
    };
}
 
Example #30
Source File: HeaderAssertionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private HeaderAssertions headerAssertions(HttpHeaders responseHeaders) {
	MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create("/"));
	MockClientHttpResponse response = new MockClientHttpResponse(HttpStatus.OK);
	response.getHeaders().putAll(responseHeaders);

	MonoProcessor<byte[]> emptyContent = MonoProcessor.create();
	emptyContent.onComplete();

	ExchangeResult result = new ExchangeResult(request, response, emptyContent, emptyContent, Duration.ZERO, null);
	return new HeaderAssertions(result, mock(WebTestClient.ResponseSpec.class));
}