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

The following examples show how to use reactor.core.publisher.MonoProcessor#create() . 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: 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 2
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 3
Source File: RSocketRequesterTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testChannelRequestServerSideCancellation() {
  MonoProcessor<Payload> cancelled = MonoProcessor.create();
  UnicastProcessor<Payload> request = UnicastProcessor.create();
  request.onNext(EmptyPayload.INSTANCE);
  rule.socket.requestChannel(request).subscribe(cancelled);
  int streamId = rule.getStreamIdForRequestType(REQUEST_CHANNEL);
  rule.connection.addToReceivedBuffer(CancelFrameCodec.encode(rule.alloc(), streamId));
  rule.connection.addToReceivedBuffer(PayloadFrameCodec.encodeComplete(rule.alloc(), streamId));
  Flux.first(
          cancelled,
          Flux.error(new IllegalStateException("Channel request not cancelled"))
              .delaySubscription(Duration.ofSeconds(1)))
      .blockFirst();

  Assertions.assertThat(request.isDisposed()).isTrue();
  Assertions.assertThat(rule.connection.getSent())
      .hasSize(1)
      .first()
      .matches(bb -> frameType(bb) == REQUEST_CHANNEL)
      .matches(ReferenceCounted::release);
  rule.assertHasNoLeaks();
}
 
Example 4
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 5
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 6
Source File: WebsocketClientOperations.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
WebsocketClientOperations(URI currentURI,
		WebsocketClientSpec websocketClientSpec,
		HttpClientOperations replaced) {
	super(replaced);
	this.proxyPing = websocketClientSpec.handlePing();
	Channel channel = channel();
	onCloseState = MonoProcessor.create();

	String subprotocols = websocketClientSpec.protocols();
	handshaker = WebSocketClientHandshakerFactory.newHandshaker(currentURI,
				WebSocketVersion.V13,
				subprotocols != null && !subprotocols.isEmpty() ? subprotocols : null,
				true,
				replaced.requestHeaders()
				        .remove(HttpHeaderNames.HOST),
				websocketClientSpec.maxFramePayloadLength());

	handshaker.handshake(channel)
	          .addListener(f -> {
		          markPersistent(false);
		          channel.read();
	          });
}
 
Example 7
Source File: ChannelOperations.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link ChannelOperations} attached to the {@link Channel}. Attach the {@link NettyPipeline#ReactiveBridge} handle.
 *
 * @param connection the new {@link Connection} connection
 * @param listener the events callback
 */
public ChannelOperations(Connection connection, ConnectionObserver listener) {
	this.connection = Objects.requireNonNull(connection, "connection");
	this.listener = Objects.requireNonNull(listener, "listener");
	this.onTerminate = MonoProcessor.create();
	this.inbound = new FluxReceive(this);
}
 
Example 8
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 9
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 10
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 11
Source File: WebsocketTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testIssue900_1() {
	MonoProcessor<WebSocketCloseStatus> statusClient = MonoProcessor.create();

	httpServer =
			HttpServer.create()
			          .port(0)
			          .handle((req, res) ->
			              res.sendWebsocket((in, out) -> out.sendObject(in.receiveFrames()
			                                                              .doOnNext(WebSocketFrame::retain))))
			          .wiretap(true)
			          .bindNow();

	Flux<WebSocketFrame> response =
			HttpClient.create()
			          .port(httpServer.port())
			          .websocket()
			          .uri("/")
			          .handle((in, out) -> {
			              in.receiveCloseStatus()
			                .subscribeWith(statusClient);

			              return out.sendObject(Flux.just(new TextWebSocketFrame("echo"),
			                                              new CloseWebSocketFrame(1008, "something")))
			                        .then()
			                        .thenMany(in.receiveFrames());
			          });

	StepVerifier.create(response)
	            .expectNextMatches(webSocketFrame ->
	                webSocketFrame instanceof TextWebSocketFrame &&
	                    "echo".equals(((TextWebSocketFrame) webSocketFrame).text()))
	            .expectComplete()
	            .verify(Duration.ofSeconds(30));

	StepVerifier.create(statusClient)
	            .expectNext(new WebSocketCloseStatus(1008, "something"))
	            .expectComplete()
	            .verify(Duration.ofSeconds(30));
}
 
Example 12
Source File: RSocketRequester.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
RSocketRequester(
    DuplexConnection connection,
    PayloadDecoder payloadDecoder,
    StreamIdSupplier streamIdSupplier,
    int mtu,
    int keepAliveTickPeriod,
    int keepAliveAckTimeout,
    @Nullable KeepAliveHandler keepAliveHandler,
    RequesterLeaseHandler leaseHandler,
    Scheduler serialScheduler) {
  this.connection = connection;
  this.allocator = connection.alloc();
  this.payloadDecoder = payloadDecoder;
  this.streamIdSupplier = streamIdSupplier;
  this.mtu = mtu;
  this.leaseHandler = leaseHandler;
  this.senders = new SynchronizedIntObjectHashMap<>();
  this.receivers = new SynchronizedIntObjectHashMap<>();
  this.onClose = MonoProcessor.create();
  this.serialScheduler = serialScheduler;

  // DO NOT Change the order here. The Send processor must be subscribed to before receiving
  this.sendProcessor = new UnboundedProcessor<>();

  connection.onClose().subscribe(null, this::tryTerminateOnConnectionError, this::tryShutdown);
  connection.send(sendProcessor).subscribe(null, this::handleSendProcessorError);

  connection.receive().subscribe(this::handleIncomingFrames, e -> {});

  if (keepAliveTickPeriod != 0 && keepAliveHandler != null) {
    KeepAliveSupport keepAliveSupport =
        new ClientKeepAliveSupport(this.allocator, keepAliveTickPeriod, keepAliveAckTimeout);
    this.keepAliveFramesAcceptor =
        keepAliveHandler.start(
            keepAliveSupport, sendProcessor::onNextPrioritized, this::tryTerminateOnKeepAlive);
  } else {
    keepAliveFramesAcceptor = null;
  }
}
 
Example 13
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 14
Source File: BulkheadSubscriberWhiteboxVerification.java    From resilience4j with Apache License 2.0 4 votes vote down vote up
@Override
public Subscriber<Integer> createSubscriber(WhiteboxSubscriberProbe<Integer> probe) {
    return new io.github.resilience4j.reactor.bulkhead.operator.BulkheadSubscriber<Integer>(
        Bulkhead.ofDefaults("verification"), MonoProcessor.create(), true) {
        @Override
        public void hookOnSubscribe(Subscription subscription) {
            super.hookOnSubscribe(subscription);

            // register a successful Subscription, and create a Puppet,
            // for the WhiteboxVerification to be able to drive its tests:
            probe.registerOnSubscribe(new SubscriberPuppet() {

                @Override
                public void triggerRequest(long elements) {
                    subscription.request(elements);
                }

                @Override
                public void signalCancel() {
                    subscription.cancel();
                }
            });
        }

        @Override
        public void hookOnNext(Integer integer) {
            super.hookOnNext(integer);
            probe.registerOnNext(integer);
        }

        @Override
        public void hookOnError(Throwable t) {
            super.hookOnError(t);
            probe.registerOnError(t);
        }

        @Override
        public void hookOnComplete() {
            super.hookOnComplete();
            probe.registerOnComplete();
        }
    };
}
 
Example 15
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 16
Source File: SimpAnnotationMethodMessageHandlerTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@MessageMapping("mono")
public Mono<String> handleMono() {
	this.mono = MonoProcessor.create();
	return this.mono;
}
 
Example 17
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 4 votes vote down vote up
@Test
public void testCancelConnectionCloseForWebSocketServer() {
	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);

	                                 in.withConnection(Connection::dispose);

	                                 return Mono.never();
	                             }))
	                             .wiretap(true)
	                             .bindNow();

	HttpClient.create()
	          .port(disposableServer.port())
	          .wiretap(true)
	          .websocket()
	          .uri("/")
	          .handle((in, out) -> {
	              in.receiveCloseStatus()
	                .subscribeWith(statusClient);

	              return Mono.never();
	          })
	          .subscribe();

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

	StepVerifier.create(statusServer)
	            .expectNext(new WebSocketCloseStatus(-1, ""))
	            .expectComplete()
	            .verify(Duration.ofSeconds(30));
}
 
Example 18
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());
  }
}
 
Example 19
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 20
Source File: VoiceWebsocketHandler.java    From Discord4J with GNU Lesser General Public License v3.0 3 votes vote down vote up
/**
 * Create a new handler with the given data pipelines.
 *
 * @param inbound the {@link FluxSink} of {@link ByteBuf} to process inbound payloads
 * @param outbound the {@link Flux} of {@link ByteBuf} to process outbound payloads
 * @param context the Reactor {@link Context} that owns this handler, to enrich logging
 */
public VoiceWebsocketHandler(FluxSink<ByteBuf> inbound, Flux<ByteBuf> outbound, Context context) {
    this.inbound = inbound;
    this.outbound = outbound;
    this.sessionClose = MonoProcessor.create();
    this.context = context;
}