reactor.core.publisher.Mono Java Examples

The following examples show how to use reactor.core.publisher.Mono. 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: QueryTests.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@Test
public void testSingle() {
	// tag::example-mono[]
	Employee e = new Employee();
	e.setFirstName("Bilbo");
	Example<Employee> example = Example.of(e);
	// end::example-mono[]

	// tag::query-mono[]
	Mono<Employee> singleEmployee = repository.findOne(example);
	// end::query-mono[]

	StepVerifier.create(singleEmployee)
		.expectNextMatches(employee -> {
			assertThat(employee).hasNoNullFieldsOrProperties();
			assertThat(employee.getFirstName()).isEqualTo("Bilbo");
			assertThat(employee.getLastName()).isEqualTo("Baggins");
			assertThat(employee.getRole()).isEqualTo("burglar");
			return true;
		})
		.expectComplete()
		.verify();
}
 
Example #2
Source File: RedissonSubscribeReactiveTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnSubscribe() {
    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 #3
Source File: StyxHttpClientTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void sendsStreamingRequests() throws ExecutionException, InterruptedException {
    LiveHttpResponse response = new StyxHttpClient.Builder()
            .build()
            .streaming()
            .send(httpRequest.stream())
            .get();

    assertThat(response.status(), is(OK));

    Mono.from(response.aggregate(10000)).block();

    server.verify(
            getRequestedFor(urlEqualTo("/"))
                    .withHeader("Host", equalTo(hostString(server.port())))
    );
}
 
Example #4
Source File: BodyInsertersTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void ofPublisher() {
	Flux<String> body = Flux.just("foo");
	BodyInserter<Flux<String>, ReactiveHttpOutputMessage> inserter = BodyInserters.fromPublisher(body, String.class);

	MockServerHttpResponse response = new MockServerHttpResponse();
	Mono<Void> result = inserter.insert(response, this.context);
	StepVerifier.create(result).expectComplete().verify();
	StepVerifier.create(response.getBody())
			.consumeNextWith(buf -> {
				String actual = DataBufferTestUtils.dumpString(buf, UTF_8);
				Assert.assertEquals("foo", actual);
			})
			.expectComplete()
			.verify();
}
 
Example #5
Source File: MonoResultFactory.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Result<List<T>> zip(List<Result<T>> results) {
	if (results.isEmpty()) {
		return just(new ArrayList<>());
	}
	List<Mono<T>> monos = new ArrayList<>();
	for (Result<T> result : results) {
		monos.add(((MonoResult) result).getMono());
	}
	Mono<List<T>> zipped = Mono.zip(monos, a -> Arrays.asList((T[]) a));
	return toResult(zipped);
}
 
Example #6
Source File: ActorProxyImplTest.java    From java-sdk with MIT License 6 votes vote down vote up
@Test()
public void invokeActorMethodWithoutDataWithVoidReturnType() {
  final DaprClient daprClient = mock(DaprClient.class);
  when(daprClient.invokeActorMethod(anyString(), anyString(), anyString(), Mockito.isNull()))
      .thenReturn(Mono.empty());

  final ActorProxy actorProxy = new ActorProxyImpl(
      "myActorType",
      new ActorId("100"),
      new DefaultObjectSerializer(),
      daprClient);

  Mono<Void> result = actorProxy.invokeActorMethod("getData");
  Void emptyResponse = result.block();
  Assert.assertNull(emptyResponse);
}
 
Example #7
Source File: ProductCompositeService.java    From Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud with MIT License 6 votes vote down vote up
/**
 * Sample usage: curl $HOST:$PORT/product-composite/1
 *
 * @param productId
 * @return the composite product info, if found, else null
 */
@ApiOperation(
    value = "${api.product-composite.get-composite-product.description}",
    notes = "${api.product-composite.get-composite-product.notes}")
@ApiResponses(value = {
    @ApiResponse(code = 400, message = "Bad Request, invalid format of the request. See response message for more information."),
    @ApiResponse(code = 404, message = "Not found, the specified id does not exist."),
    @ApiResponse(code = 422, message = "Unprocessable entity, input parameters caused the processing to fail. See response message for more information.")
})
@GetMapping(
    value    = "/product-composite/{productId}",
    produces = "application/json")
Mono<ProductAggregate> getCompositeProduct(
    @PathVariable int productId,
    @RequestParam(value = "delay", required = false, defaultValue = "0") int delay,
    @RequestParam(value = "faultPercent", required = false, defaultValue = "0") int faultPercent
);
 
Example #8
Source File: RedissonReactiveHashCommands.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Override
public Flux<MultiValueResponse<HGetCommand, ByteBuffer>> hMGet(Publisher<HGetCommand> commands) {
    return execute(commands, command -> {
        
        Assert.notNull(command.getKey(), "Key must not be null!");
        Assert.notNull(command.getFields(), "Fields must not be null!");
        
        byte[] keyBuf = toByteArray(command.getKey());
        List<Object> args = new ArrayList<Object>(command.getFields().size() + 1);
        args.add(keyBuf);
        args.addAll(command.getFields().stream().map(buf -> toByteArray(buf)).collect(Collectors.toList()));
        Mono<List<byte[]>> m = read(keyBuf, ByteArrayCodec.INSTANCE, HMGET, args.toArray());
        return m.map(v -> {
            List<ByteBuffer> values = v.stream().map(array -> {
                if (array != null) {
                    return ByteBuffer.wrap(array);
                }
                return null;
            }).collect(Collectors.toList());
            return new MultiValueResponse<>(command, values);
        });
    });
}
 
Example #9
Source File: TestKit.java    From r2dbc-spi with Apache License 2.0 6 votes vote down vote up
@Test
default void returnGeneratedValues() {

    getJdbcOperations().execute("DROP TABLE test");
    getJdbcOperations().execute(getCreateTableWithAutogeneratedKey());

    Mono.from(getConnectionFactory().create())
        .flatMapMany(connection -> {
            Statement statement = connection.createStatement(getInsertIntoWithAutogeneratedKey());

            statement.returnGeneratedValues();

            return Flux.from(statement
                .execute())
                .concatWith(close(connection)).flatMap(it -> it.map((row, rowMetadata) -> row.get(0)));
        })
        .as(StepVerifier::create)
        .expectNextCount(1)
        .verifyComplete();
}
 
Example #10
Source File: TokenService.java    From Learning-Path-Spring-5-End-to-End-Programming with MIT License 6 votes vote down vote up
@HystrixCommand(commandKey = "request-token",groupKey = "auth-operations",commandProperties = {
    @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
    @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "10"),
    @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"),
    @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000")
})
public Mono<AccessToken> token(Credentials credentials) {
  val authorizationHeader = Base64Utils.encodeToString(( credentials.getClientId() + ":" + credentials.getClientSecret()).getBytes());
  return discoveryService.serviceAddressFor(this.authService).next().flatMap(address ->
      this.webClient.mutate().baseUrl(address + "/" + this.authServiceApiPath).build()
      .post()
      .contentType(MediaType.APPLICATION_FORM_URLENCODED)
      .header("Authorization","Basic " + authorizationHeader)
      .body(BodyInserters.fromFormData("grant_type", "client_credentials"))
      .retrieve()
      .onStatus(HttpStatus::is4xxClientError, clientResponse ->
          Mono.error(new RuntimeException("Invalid call"))
      ).onStatus(HttpStatus::is5xxServerError, clientResponse ->
      Mono.error(new RuntimeException("Error on server"))
  ).bodyToMono(AccessToken.class));
}
 
Example #11
Source File: HttpServerOperations.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public NettyOutbound sendHeaders() {
	if (hasSentHeaders()) {
		return this;
	}

	return then(Mono.empty());
}
 
Example #12
Source File: HttpHeadResponseDecorator.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Apply {@link Flux#reduce(Object, BiFunction) reduce} on the body, count
 * the number of bytes produced, release data buffers without writing, and
 * set the {@literal Content-Length} header.
 */
@Override
public final Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
	return Flux.from(body)
			.reduce(0, (current, buffer) -> {
				int next = current + buffer.readableByteCount();
				DataBufferUtils.release(buffer);
				return next;
			})
			.doOnNext(count -> getHeaders().setContentLength(count))
			.then();
}
 
Example #13
Source File: RedissonReactiveStringCommands.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<ByteBufferResponse<RangeCommand>> getRange(Publisher<RangeCommand> commands) {
    return execute(commands, command -> {

        Assert.notNull(command.getKey(), "Key must not be null!");
        Assert.notNull(command.getRange(), "Range must not be null!");

        byte[] keyBuf = toByteArray(command.getKey());
        Mono<byte[]> m = read(keyBuf, ByteArrayCodec.INSTANCE, GETRANGE, 
                keyBuf, command.getRange().getLowerBound().getValue().orElse(0L), 
                        command.getRange().getUpperBound().getValue().orElse(-1L));
        return m.map(v -> new ByteBufferResponse<>(command, ByteBuffer.wrap(v)));
    });
}
 
Example #14
Source File: UserMailboxesService.java    From james-project with Apache License 2.0 5 votes vote down vote up
public boolean testMailboxExists(Username username, MailboxName mailboxName) throws MailboxException, UsersRepositoryException {
    usernamePreconditions(username);
    MailboxSession mailboxSession = mailboxManager.createSystemSession(username);
    MailboxPath mailboxPath = MailboxPath.forUser(username, mailboxName.asString())
        .assertAcceptable(mailboxSession.getPathDelimiter());
    return Mono.from(mailboxManager.mailboxExists(mailboxPath, mailboxSession))
        .block();
}
 
Example #15
Source File: MailboxManagerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void hasInboxShouldBeFalseWhenINBOXIsNotCreated() throws Exception {
    session = mailboxManager.createSystemSession(USER_1);
    mailboxManager.startProcessingRequest(session);

    assertThat(Mono.from(mailboxManager.hasInbox(session)).block()).isFalse();
}
 
Example #16
Source File: DeleteMessageListener.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Mono<Void> handleMessageDeletionAsPartOfMailboxDeletion(CassandraMessageId messageId, CassandraId excludedId) {
    return Mono.just(messageId)
        .filterWhen(id -> isReferenced(id, excludedId))
        .flatMap(id -> readMessage(id)
            .flatMap(message -> deleteUnreferencedAttachments(message).thenReturn(message))
            .flatMap(this::deleteAttachmentMessageIds)
            .then(messageDAO.delete(messageId)));
}
 
Example #17
Source File: DefaultEntityResponseBuilderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void contentLength() {
	String body = "foo";
	Mono<EntityResponse<String>> result = EntityResponse.fromObject(body).contentLength(42).build();
	StepVerifier.create(result)
			.expectNextMatches(response -> Long.valueOf(42).equals(response.headers().getContentLength()))
			.expectComplete()
			.verify();
}
 
Example #18
Source File: ExampleServiceInstanceService.java    From spring-cloud-open-service-broker with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<GetServiceInstanceResponse> getServiceInstance(GetServiceInstanceRequest request) {
	String serviceInstanceId = request.getServiceInstanceId();

	//
	// retrieve the details of the specified service instance
	//

	String dashboardUrl = ""; /* retrieve dashboard URL */

	return Mono.just(GetServiceInstanceResponse.builder()
			.dashboardUrl(dashboardUrl)
			.build());
}
 
Example #19
Source File: RegexRequestPathRewriter.java    From charon-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<HttpResponse> forward(HttpRequest request, HttpRequestExecution execution) {
    logStart(execution.getMappingName());
    rewritePath(request.url(), request::setUrl);
    return execution.execute(request)
            .doOnSuccess(response -> logEnd(execution.getMappingName()));
}
 
Example #20
Source File: CommonPoolTest.java    From reactor-pool with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("allPools")
void allocatorErrorInWarmupIsPropagated(Function<PoolBuilder<Object, ?>, AbstractPool<Object>> configAdjuster) {
	final PoolBuilder<Object, ?> builder = PoolBuilder
			.from(Mono.error(new IllegalStateException("boom")))
			.sizeBetween(1, 1)
			.evictionPredicate((poolable, metadata) -> true);
	AbstractPool<Object> pool = configAdjuster.apply(builder);

	StepVerifier.create(pool.warmup())
	            .verifyErrorSatisfies(e -> assertThat(e).isInstanceOf(IllegalStateException.class)
	                                                    .hasMessage("boom"));
}
 
Example #21
Source File: MessageHandlerAcceptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<RSocket> accept(ConnectionSetupPayload setupPayload, RSocket sendingRSocket) {
	MessagingRSocket rsocket = createRSocket(sendingRSocket);

	// Allow handling of the ConnectionSetupPayload via @MessageMapping methods.
	// However, if the handling is to make requests to the client, it's expected
	// it will do so decoupled from the handling, e.g. via .subscribe().
	return rsocket.handleConnectionSetupPayload(setupPayload).then(Mono.just(rsocket));
}
 
Example #22
Source File: DiscoveryService.java    From Spring-5.0-By-Example with MIT License 5 votes vote down vote up
public Flux<String> serviceAddressFor(String service) {
  return Flux.defer(() ->  Flux.just(this.dClient.getInstances(service)).flatMap(srv ->
      Mono.just(this.lbClient.choose(service))
  ).flatMap(serviceInstance ->
      Mono.just(serviceInstance.getUri().toString())
  ));
}
 
Example #23
Source File: FreeCapacityFetcherProto.java    From linstor-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Mono<Map<StorPool.Key, Tuple2<SpaceInfo, List<ApiCallRc>>>> fetchThinFreeSpaceInfo(Set<NodeName> nodesFilter)
{
    return scopeRunner.fluxInTransactionalScope(
        "Fetch thin capacity info",
        lockGuardFactory.buildDeferred(LockType.READ, LockObj.NODES_MAP, LockObj.STOR_POOL_DFN_MAP),
        () -> assembleRequests(nodesFilter).flatMap(this::parseFreeSpaces)
    )
        .collectMap(
        t -> t.getT1(),
        t -> t.getT2()
    );
}
 
Example #24
Source File: ServiceInstanceBindingEventServiceTest.java    From spring-cloud-open-service-broker with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<CreateServiceInstanceBindingResponse> createServiceInstanceBinding(
		CreateServiceInstanceBindingRequest request) {
	if (request.getServiceDefinitionId() == null) {
		return Mono.error(new ServiceInstanceBindingExistsException("service-instance-id", "arrrr"));
	}
	return Mono.just(CreateServiceInstanceAppBindingResponse.builder().build());
}
 
Example #25
Source File: MessageFastViewProjectionContract.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
default void storeShouldOverrideOldRecord() {
    MessageId messageId = newMessageId();
    Mono.from(testee().store(messageId, MESSAGE_FAST_VIEW_PRECOMPUTED_PROPERTIES_1))
        .block();

    Mono.from(testee().store(messageId, MESSAGE_FAST_VIEW_PRECOMPUTED_PROPERTIES_2))
        .block();

    assertThat(Mono.from(testee().retrieve(messageId)).block())
        .isEqualTo(MESSAGE_FAST_VIEW_PRECOMPUTED_PROPERTIES_2);
}
 
Example #26
Source File: CassandraEventDeadLetters.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<InsertionId> store(Group registeredGroup, Event failDeliveredEvent) {
    Preconditions.checkArgument(registeredGroup != null, REGISTERED_GROUP_CANNOT_BE_NULL);
    Preconditions.checkArgument(failDeliveredEvent != null, FAIL_DELIVERED_EVENT_CANNOT_BE_NULL);

    InsertionId insertionId = InsertionId.random();
    return cassandraEventDeadLettersDAO.store(registeredGroup, failDeliveredEvent, insertionId)
        .then(cassandraEventDeadLettersGroupDAO.storeGroup(registeredGroup))
        .thenReturn(insertionId);
}
 
Example #27
Source File: CassandraReIndexerImplTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setUp(CassandraCluster cassandra) {
    mailboxManager = CassandraMailboxManagerProvider.provideMailboxManager(cassandra, PreDeletionHooks.NO_PRE_DELETION_HOOK);
    MailboxSessionMapperFactory mailboxSessionMapperFactory = mailboxManager.getMapperFactory();
    messageSearchIndex = mock(ListeningMessageSearchIndex.class);
    when(messageSearchIndex.add(any(), any(), any())).thenReturn(Mono.empty());
    when(messageSearchIndex.deleteAll(any(), any())).thenReturn(Mono.empty());
    reIndexer = new ReIndexerImpl(new ReIndexerPerformer(mailboxManager, messageSearchIndex, mailboxSessionMapperFactory),
        mailboxManager, mailboxSessionMapperFactory);
}
 
Example #28
Source File: AbstractReactiveTransactionAspectTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void checkReactiveTransaction(boolean expected) {
	Mono.subscriberContext().handle((context, sink) -> {
		if (context.hasKey(TransactionContext.class) != expected){
			fail("Should have thrown NoTransactionException");
		}
		sink.complete();
	}).block();
}
 
Example #29
Source File: JdbcRouteDefinitionLocator.java    From open-cloud with MIT License 5 votes vote down vote up
/**
 * 刷新路由
 *
 * @return
 */
public Mono<Void> refresh() {
    this.loadRoutes();
    // 触发默认路由刷新事件,刷新缓存路由
    this.publisher.publishEvent(new RefreshRoutesEvent(this));
    return Mono.empty();
}
 
Example #30
Source File: RestServiceHelper.java    From reactive-ms-example with MIT License 5 votes vote down vote up
private static <T> Mono<T> getMonoFromJson(final String json, final Class<T> type) {
    final ObjectMapper objectMapper = new ObjectMapper();
    try {
        return Mono.just(objectMapper.readValue(json, type));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}