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

The following examples show how to use reactor.core.publisher.Mono#block() . These examples are extracted from open source projects. 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
@Test
public void testSubscribe() {
    RedissonConnectionFactory factory = new RedissonConnectionFactory(redisson);
    ReactiveRedisConnection connection = factory.getReactiveConnection();
    Mono<ReactiveSubscription> s = connection.pubSubCommands().createSubscription();
    AtomicReference<byte[]> msg = new AtomicReference<byte[]>();
    ReactiveSubscription ss = s.block();

    ss.subscribe(ByteBuffer.wrap("test".getBytes())).block();
    ss.receive().doOnEach(message -> {
        msg.set(message.get().getMessage().array());
    }).subscribe();
    
    connection.pubSubCommands().publish(ByteBuffer.wrap("test".getBytes()), ByteBuffer.wrap("msg".getBytes())).block();

    Awaitility.await().atMost(Duration.ONE_SECOND)
                .until(() -> Arrays.equals("msg".getBytes(), msg.get()));
    
    ss.unsubscribe();
    
    connection.pubSubCommands().publish(ByteBuffer.wrap("test".getBytes()), ByteBuffer.wrap("msg".getBytes())).block();
}
 
Example 2
@Test(timeout = 10_000L)
public void downloadAllAndConvertToJavaMap() throws Exception {
	//given
	final Flux<Domain> domains = Domains.all();

	//when
	final Mono<Map<URI, Html>> mapStream = null; // TODO

	//then
	final Map<URI, Html> map = mapStream.block();

	assertThat(map)
			.hasSize(500)
			.containsEntry(new URI("http://archive.org"), new Html("<html><title>http://archive.org</title></html>"))
			.containsEntry(new URI("http://github.com"), new Html("<html><title>http://github.com</title></html>"));

	map.forEach((key, value) ->
			assertThat(value.getRaw()).contains(key.getHost())
	);
}
 
Example 3
Source Project: java-sdk   File: DaprClientGrpcTest.java    License: MIT License 6 votes vote down vote up
@Test
public void deleteStateRetryPolicyNoPatternTest() {
  String etag = "ETag1";
  String key = "key1";
  StateOptions options = buildStateOptions(StateOptions.Consistency.STRONG, StateOptions.Concurrency.FIRST_WRITE,
      Duration.ofDays(100), 1, null);
  SettableFuture<Empty> settableFuture = SettableFuture.create();
  MockCallback<Empty> callback = new MockCallback<>(Empty.newBuilder().build());
  addCallback(settableFuture, callback, directExecutor());
  when(client.deleteState(any(io.dapr.v1.DaprProtos.DeleteStateRequest.class)))
      .thenReturn(settableFuture);
  State<String> stateKey = buildStateKey(null, key, etag, options);
  Mono<Void> result = adapter.deleteState(STATE_STORE_NAME, stateKey.getKey(), stateKey.getEtag(),
      stateKey.getOptions());
  settableFuture.set(Empty.newBuilder().build());
  result.block();
  assertTrue(callback.wasCalled);
}
 
Example 4
Source Project: java-sdk   File: DaprClientGrpcTest.java    License: MIT License 6 votes vote down vote up
@Test
public void invokeServiceNoRequestBodyObjectTest() throws Exception {
  MyObject object = new MyObject(1, "Value");
  SettableFuture<CommonProtos.InvokeResponse> settableFuture = SettableFuture.create();

  MockCallback<CommonProtos.InvokeResponse> callback =
      new MockCallback<CommonProtos.InvokeResponse>(CommonProtos.InvokeResponse.newBuilder()
          .setData(getAny(object)).build());
  addCallback(settableFuture, callback, directExecutor());
  settableFuture.set(CommonProtos.InvokeResponse.newBuilder().setData(getAny(object)).build());
  when(client.invokeService(any(DaprProtos.InvokeServiceRequest.class)))
      .thenReturn(settableFuture);
  Mono<MyObject> result = adapter.invokeService(Verb.GET, "appId", "method", null, MyObject.class);
  MyObject resultObject = result.block();
  assertEquals(object.id, resultObject.id);
  assertEquals(object.value, resultObject.value);
}
 
Example 5
@Test
public void shouldSendTraceContextToServer_rootSpan() throws Exception {
	disposableServer = HttpServer.create().port(0)
			// this reads the trace context header, b3, returning it in the response
			.handle((in, out) -> out
					.sendString(Flux.just(in.requestHeaders().get("b3"))))
			.bindNow();

	Mono<String> request = httpClient.port(disposableServer.port()).get().uri("/")
			.responseContent().aggregate().asString();

	String b3SingleHeaderReadByServer = request.block();

	MutableSpan clientSpan = spanHandler.takeRemoteSpan(CLIENT);

	assertThat(b3SingleHeaderReadByServer)
			.isEqualTo(clientSpan.traceId() + "-" + clientSpan.id() + "-1");
}
 
Example 6
Source Project: java-sdk   File: DaprClientGrpcTest.java    License: MIT License 6 votes vote down vote up
@Test
public void stateOptionsConcurrencyValuesHaveValidGrpcEnumMappings() {
  String key = "key1";
  String etag = "ETag1";
  String value = "State value";
  SettableFuture<Empty> settableFuture = SettableFuture.create();
  MockCallback<Empty> callback = new MockCallback<>(Empty.newBuilder().build());
  addCallback(settableFuture, callback, directExecutor());
  when(client.saveState(any(io.dapr.v1.DaprProtos.SaveStateRequest.class))).thenReturn(settableFuture);
  settableFuture.set(Empty.newBuilder().build());
  for (StateOptions.Concurrency concurrency : StateOptions.Concurrency.values()) {
    StateOptions options = buildStateOptions(StateOptions.Consistency.EVENTUAL, concurrency,
            Duration.ofDays(100), null, StateOptions.RetryPolicy.Pattern.LINEAR);
    Mono<Void> result = adapter.saveState(STATE_STORE_NAME, key, etag, value, options);
    result.block();
  }

  assertTrue(callback.wasCalled);
}
 
Example 7
Source Project: java-sdk   File: GRPCStateClientIT.java    License: MIT License 5 votes vote down vote up
@Test
public void saveAndGetState() {

  //The key use to store the state
  final String stateKey = "myKey";

  //create the http client


  //creation of a dummy data
  MyData data = new MyData();
  data.setPropertyA("data in property A");
  data.setPropertyB("data in property B");

  //create of the deferred call to DAPR to store the state
  Mono<Void> saveResponse = daprClient.saveState(STATE_STORE_NAME, stateKey, null, data, null);
  //execute the save action
  saveResponse.block();

  //create of the deferred call to DAPR to get the state
  Mono<State<MyData>> response = daprClient.getState(STATE_STORE_NAME, new State(stateKey, null, null), MyData.class);

  //retrieve the state
  State<MyData> myDataResponse = response.block();

  //Assert that the response is the correct one
  assertNotNull(myDataResponse.getEtag());
  assertNotNull(myDataResponse.getKey());
  assertNotNull(myDataResponse.getValue());
  assertEquals("data in property A", myDataResponse.getValue().getPropertyA());
  assertEquals("data in property B", myDataResponse.getValue().getPropertyB());
}
 
Example 8
@Override
public Product createProduct(Product body) {

    if (body.getProductId() < 1) throw new InvalidInputException("Invalid productId: " + body.getProductId());

    ProductEntity entity = mapper.apiToEntity(body);
    Mono<Product> newEntity = repository.save(entity)
        .log()
        .onErrorMap(
            DuplicateKeyException.class,
            ex -> new InvalidInputException("Duplicate key, Product Id: " + body.getProductId()))
        .map(e -> mapper.entityToApi(e));

    return newEntity.block();
}
 
Example 9
@Test
public void testRetrieveOrgId() {
	CFAccessorSimulator subject = new CFAccessorSimulator(2);
	Mono<ListOrganizationsResponse> mono = subject.retrieveOrgId("simorg");
	ListOrganizationsResponse result = mono.block();
	Assert.assertEquals(CFAccessorSimulator.ORG_UUID, result.getResources().get(0).getMetadata().getId());
}
 
Example 10
Source Project: reactor-netty   File: HttpClientTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void backpressured() throws Exception {
	Path resource = Paths.get(getClass().getResource("/public").toURI());
	disposableServer = HttpServer.create()
	                             .port(0)
	                             .route(routes -> routes.directory("/test", resource))
	                             .wiretap(true)
	                             .bindNow();

	ByteBufFlux remote =
			createHttpClientForContextWithPort()
			        .get()
			        .uri("/test/test.css")
			        .responseContent();

	Mono<String> page = remote.asString()
	                          .limitRate(1)
	                          .reduce(String::concat);

	Mono<String> cancelledPage = remote.asString()
	                                   .take(5)
	                                   .limitRate(1)
	                                   .reduce(String::concat);

	page.block(Duration.ofSeconds(30));
	cancelledPage.block(Duration.ofSeconds(30));
	page.block(Duration.ofSeconds(30));
}
 
Example 11
Source Project: java-sdk   File: DaprClientGrpcTest.java    License: MIT License 5 votes vote down vote up
@Test(expected = RuntimeException.class)
public void invokeServiceVoidExceptionThrownTest() {
  when(client.invokeService(any(DaprProtos.InvokeServiceRequest.class)))
      .thenThrow(RuntimeException.class);
  Mono<Void> result = adapter.invokeService(Verb.GET, "appId", "method", "request");
  result.block();
}
 
Example 12
Source Project: java-sdk   File: DaprRuntimeTest.java    License: MIT License 5 votes vote down vote up
@Test(expected = RuntimeException.class)
public void subscribeCallbackException() throws Exception {
  Assert.assertNotNull(this.daprRuntime.getSubscribedTopics());
  Assert.assertTrue(this.daprRuntime.getSubscribedTopics().isEmpty());

  TopicListener listener = mock(TopicListener.class);
  when(listener.process(any(), any()))
          .thenReturn(Mono.error(new RuntimeException()));

  this.daprRuntime.subscribeToTopic(TOPIC_NAME, listener);

  Message message = new Message(
          generateMessageId(),
          TYPE_PLAIN_TEXT,
          generatePayload(),
          generateSingleMetadata());

  Mono<byte[]> result = this.daprRuntime
          .handleInvocation(TOPIC_NAME, this.serialize(message), message.metadata);

  CloudEvent envelope = new CloudEvent(
    message.id,
    null,
    null,
    null,
    message.datacontenttype,
    message.data
  );
  verify(listener, times(1)).process(eq(envelope), eq(message.metadata));
  result.block();
}
 
Example 13
@Override
public Product createProduct(Product body) {

    if (body.getProductId() < 1) throw new InvalidInputException("Invalid productId: " + body.getProductId());

    ProductEntity entity = mapper.apiToEntity(body);
    Mono<Product> newEntity = repository.save(entity)
        .log(null, FINE)
        .onErrorMap(
            DuplicateKeyException.class,
            ex -> new InvalidInputException("Duplicate key, Product Id: " + body.getProductId()))
        .map(e -> mapper.entityToApi(e));

    return newEntity.block();
}
 
Example 14
Source Project: reactor-netty   File: HttpSendFileTests.java    License: Apache License 2.0 5 votes vote down vote up
private void assertSendFile(Function<HttpServerResponse, NettyOutbound> fn, boolean compression, int compressionSize,
		BiPredicate<HttpServerRequest, HttpServerResponse> compressionPredicate, Consumer<String> bodyAssertion) {
	HttpServer server = HttpServer.create();
	if (compressionPredicate != null) {
		server = server.compress(compressionPredicate);
	}
       if (compressionSize > -1) {
		server = server.compress(compressionSize);
	}
	DisposableServer context =
			customizeServerOptions(server)
			          .handle((req, resp) -> fn.apply(resp))
			          .wiretap(true)
			          .bindNow();

	HttpClient client;
	if (compression) {
		client = HttpClient.create()
		                   .remoteAddress(context::address)
		                   .compress(true);
	}
	else {
		client = HttpClient.create()
		                   .remoteAddress(context::address);
	}
	Mono<String> response =
			customizeClientOptions(client)
			          .wiretap(true)
			          .get()
			          .uri("/foo")
			          .responseSingle((res, byteBufMono) -> byteBufMono.asString(StandardCharsets.UTF_8));

	String body = response.block(Duration.ofSeconds(5));

	context.disposeNow();

	bodyAssertion.accept(body);
}
 
Example 15
@TaskAction
public void deleteApp() {
    CloudFoundryOperations cfOperations = getCfOperations();
    CfProperties cfProperties = getCfProperties();

    Mono<Void> resp = deleteDelegate.deleteApp(cfOperations, cfProperties);
    resp.block(Duration.ofMillis(defaultWaitTimeout));
}
 
Example 16
@Test
@SuppressWarnings({"rawtype", "unchecked"})
public void shouldBeRetrieableConnectionSharedReconnectableInstanceOfRSocketMono() {
  ClientTransport transport = Mockito.mock(ClientTransport.class);
  Mockito.when(transport.connect())
      .thenThrow(UncheckedIOException.class)
      .thenThrow(UncheckedIOException.class)
      .thenThrow(UncheckedIOException.class)
      .thenThrow(UncheckedIOException.class)
      .thenReturn(new TestClientTransport().connect());
  Mono<RSocket> rSocketMono =
      RSocketConnector.create()
          .reconnect(
              Retry.backoff(4, Duration.ofMillis(100))
                  .maxBackoff(Duration.ofMillis(500))
                  .doAfterRetry(onRetry()))
          .connect(transport);

  RSocket rSocket1 = rSocketMono.block();
  RSocket rSocket2 = rSocketMono.block();

  Assertions.assertThat(rSocket1).isEqualTo(rSocket2);
  assertRetries(
      UncheckedIOException.class,
      UncheckedIOException.class,
      UncheckedIOException.class,
      UncheckedIOException.class);
}
 
Example 17
@Test
void reactiveWrapBlocking() {
  log.info("Reactive Mono.fromCallable");

  Mono<Book> blockingWrapper = Mono.fromCallable(() ->
      bookRepository.findById(this.poeaa.getId()).orElse(null))
      .subscribeOn(Schedulers.boundedElastic());

  Book book = blockingWrapper.block();
  assertThat(book).satisfies(equalTo(this.poeaa));
}
 
Example 18
Source Project: java-sdk   File: DaprClientGrpcTest.java    License: MIT License 5 votes vote down vote up
@Test(expected = RuntimeException.class)
public void invokeServiceByteRequestExceptionThrownTest() throws IOException {
  when(client.invokeService(any(DaprProtos.InvokeServiceRequest.class)))
      .thenThrow(RuntimeException.class);
  String request = "Request";
  byte[] byteRequest = serializer.serialize(request);
  Mono<byte[]> result = adapter.invokeService(Verb.GET, "appId", "method", byteRequest, byte[].class);
  result.block();
}
 
Example 19
Source Project: java-sdk   File: HttpStateClientIT.java    License: MIT License 4 votes vote down vote up
@Test()
public void saveUpdateAndGetStateWithEtagAndStateOptionsLastWrite() {
  final String stateKey = "keyToBeUpdatedWithEtagAndOptions";

  //create option with concurrency with first writte and consistency of strong
  StateOptions stateOptions = new StateOptions(StateOptions.Consistency.STRONG, StateOptions.Concurrency.LAST_WRITE
      , null);

  //create dapr client
  DaprClient daprClient = buildDaprClient();
  //create Dummy data
  MyData data = new MyData();
  data.setPropertyA("data in property A");
  data.setPropertyB("data in property B");

  //create state using stateOptions
  Mono<Void> saveResponse = daprClient.saveState(STATE_STORE_NAME, stateKey, null, data, stateOptions);
  //execute the save state
  saveResponse.block();


  //crate deferred action to retrieve the state
  Mono<State<MyData>> response = daprClient.getState(STATE_STORE_NAME, new State(stateKey, null, stateOptions),
      MyData.class);
  //execute the retrieve of the state using options
  State<MyData> myDataResponse = response.block();

  Assert.assertNotNull(myDataResponse.getEtag());
  Assert.assertNotNull(myDataResponse.getKey());
  Assert.assertNotNull(myDataResponse.getValue());
  Assert.assertEquals("data in property A", myDataResponse.getValue().getPropertyA());
  Assert.assertEquals("data in property B", myDataResponse.getValue().getPropertyB());

  //change data to be udpated
  data.setPropertyA("data in property A2");
  data.setPropertyB("data in property B2");
  //create deferred action to update the action with options
  saveResponse = daprClient.saveState(STATE_STORE_NAME, stateKey, myDataResponse.getEtag(), data, stateOptions);
  //update the state
  saveResponse.block();


  data.setPropertyA("last write");
  data.setPropertyB("data in property B2");
  //create deferred action to update the action with the same etag
  saveResponse = daprClient.saveState(STATE_STORE_NAME, stateKey, myDataResponse.getEtag(), data, stateOptions);
  //update the state without an error
  saveResponse.block();

  response = daprClient.getState(STATE_STORE_NAME, new State(stateKey, null, stateOptions), MyData.class);
  State<MyData> myLastDataResponse = response.block();

  Assert.assertNotNull(myLastDataResponse.getEtag());
  Assert.assertNotNull(myLastDataResponse.getKey());
  Assert.assertNotNull(myLastDataResponse.getValue());
  Assert.assertNotNull(myDataResponse.getEtag(), myLastDataResponse.getEtag());
  Assert.assertEquals("last write", myLastDataResponse.getValue().getPropertyA());
  Assert.assertEquals("data in property B2", myLastDataResponse.getValue().getPropertyB());
}
 
Example 20
@DataProvider(value = {
        "MANUAL_IMPORT_ONLY                     |   true",
        "COMPONENT_SCAN_ONLY                    |   true",
        "COMPONENT_SCAN_WITHOUT_REACTOR_SUPPORT |   false",
        "BOTH_MANUAL_AND_COMPONENT_SCAN         |   true"
}, splitBy = "\\|")
@Test
public void project_reactor_wingtips_integration_should_work_as_expected_when_using_subscribeOn(
    ComponentTestSetup componentTestSetup,
    boolean expectTracingToPropagate
) {
    // given
    int serverPort = findFreePort();
    Class<?> mainClass = componentTestSetup.mainClass;

    ConfigurableApplicationContext serverAppContext = SpringApplication.run(
        mainClass, "--server.port=" + serverPort
    );

    try {
        // given
        // Setup the mono before we even start the trace.
        Mono<Pair<Long, Span>> asyncThreadAndTraceId =
            Mono.just("test")
                // Return the thread ID and current span.
                .map(s -> Pair.of(Thread.currentThread().getId(), Tracer.getInstance().getCurrentSpan()))
                // Set up an async boundary using subscribeOn(...).
                //      WARNING: This MUST be a new*() (e.g. newElastic()), rather than the built-in defaults
                //      like Schedulers.elastic(). Otherwise it's a race condition, as the schedulers are cached
                //      after they are created and used, so setting the Wingtips+Reactor scheduler hook after
                //      a default scheduler has been used won't work. Think one test running without the hook, and
                //      then a different test trying to run with the hook. The second test won't work.
                //      By using a new scheduler, we guarantee that it will receive whatever hook we setup as part
                //      of *this* test.
                .subscribeOn(Schedulers.newElastic("someNewElasticScheduler"));

        // Start the trace and track the thread ID we're on.
        final Span rootSpan = Tracer.getInstance().startRequestWithRootSpan("root");
        final long mainThreadId = Thread.currentThread().getId();

        // when
        // This block() is where the subscription occurs, and therefore where the
        //      ProjectReactor+Wingtips magic occurs. It should take the tracing state on the current thread here
        //      when block() is called, and propagate it into the Mono execution.
        Pair<Long, Span> result = asyncThreadAndTraceId.block();

        // then
        // The thread in the Mono.map(...) should always be different than our main thread
        //      thanks to the subscribeOn(...).
        assertThat(result.getLeft()).isNotEqualTo(mainThreadId);

        // If expectTracingToPropagate is true, then we expect the span in the Mono.map(...) to match the root span.
        //      Otherwise, the current span when Mono.map(...) executed should be null.
        if (expectTracingToPropagate) {
            assertThat(result.getRight()).isEqualTo(rootSpan);
        }
        else {
            assertThat(result.getRight()).isNull();
        }
        Tracer.getInstance().completeRequestSpan();
    } finally {
        Schedulers.removeExecutorServiceDecorator(WingtipsReactorInitializer.WINGTIPS_SCHEDULER_KEY);
        SpringApplication.exit(serverAppContext);
    }
}