Java Code Examples for reactor.core.publisher.Mono

The following examples show how to use reactor.core.publisher.Mono. 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
Source Project: styx   Author: HotelsDotCom   File: StyxHttpClientTest.java    License: 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 #2
Source Project: redisson   Author: redisson   File: RedissonReactiveHashCommands.java    License: 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 #3
Source Project: Learning-Path-Spring-5-End-to-End-Programming   Author: PacktPublishing   File: TokenService.java    License: 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 #4
Source Project: Hands-On-Microservices-with-Spring-Boot-and-Spring-Cloud   Author: PacktPublishing   File: ProductCompositeService.java    License: 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 #5
Source Project: Learning-Spring-Boot-2.0-Second-Edition   Author: PacktPublishing   File: QueryTests.java    License: 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 #6
Source Project: spring-analysis-note   Author: Vip-Augus   File: BodyInsertersTests.java    License: 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 #7
Source Project: r2dbc-spi   Author: r2dbc   File: TestKit.java    License: 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 #8
Source Project: redisson   Author: redisson   File: RedissonSubscribeReactiveTest.java    License: 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 #9
Source Project: java-sdk   Author: dapr   File: ActorProxyImplTest.java    License: 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 #10
Source Project: james-project   Author: apache   File: MailboxManagerTest.java    License: 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 #11
Source Project: james-project   Author: apache   File: SolveMailboxInconsistenciesService.java    License: Apache License 2.0 5 votes vote down vote up
private Mono<Inconsistency> detectInconsistency(CassandraIdAndPath pathRegistration) {
    return mailboxDAO.retrieveMailbox(pathRegistration.getCassandraId())
        .map(mailbox -> {
            if (mailbox.generateAssociatedPath().equals(pathRegistration.getMailboxPath())) {
                return NO_INCONSISTENCY;
            }
            // Mailbox references another path
            return new ConflictingEntryInconsistency(mailbox, pathRegistration);
        })
        .defaultIfEmpty(new OrphanMailboxPathDAOEntry(pathRegistration));
}
 
Example #12
Source Project: james-project   Author: apache   File: BlobStoreCacheContract.java    License: Apache License 2.0 5 votes vote down vote up
@Test
default void readShouldReturnEmptyCachedByteArray() {
    BlobId blobId = blobIdFactory().randomId();
    byte[] emptyByteArray = new byte[] {};

    Mono.from(testee().cache(blobId, emptyByteArray)).block();

    assertThat(new ByteArrayInputStream(Mono.from(testee().read(blobId)).block()))
        .hasSameContentAs(new ByteArrayInputStream(emptyByteArray));
}
 
Example #13
Source Project: spring-analysis-note   Author: Vip-Augus   File: DefaultEntityResponseBuilderTests.java    License: 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 #14
Source Project: titus-control-plane   Author: Netflix   File: RemoteAgentManagementClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> updateAgentInstanceAttributes(String instanceId, Map<String, String> attributes) {
    return stub.updateAgentInstanceAttributes(AgentInstanceAttributesUpdate.newBuilder()
            .setAgentInstanceId(instanceId)
            .putAllAttributes(attributes)
            .build()
    );
}
 
Example #15
Source Project: redisson   Author: redisson   File: RedissonReactiveStreamCommands.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Flux<ReactiveRedisConnection.NumericResponse<ReactiveRedisConnection.KeyCommand, Long>> xTrim(Publisher<TrimCommand> publisher) {
    return execute(publisher, command -> {

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

        byte[] k = toByteArray(command.getKey());

        Mono<Long> m = write(k, StringCodec.INSTANCE, RedisCommands.XTRIM, k, "MAXLEN", command.getCount());
        return m.map(v -> new ReactiveRedisConnection.NumericResponse<>(command, v));
    });
}
 
Example #16
Source Project: redisson   Author: redisson   File: RedissonReactiveSetCommands.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Flux<NumericResponse<SDiffStoreCommand, Long>> sDiffStore(Publisher<SDiffStoreCommand> commands) {
    return execute(commands, command -> {

        Assert.notNull(command.getKeys(), "Keys must not be null!");
        Assert.notNull(command.getKey(), "Destination key must not be null!");

        List<Object> args = new ArrayList<Object>(command.getKeys().size() + 1);
        args.add(toByteArray(command.getKey()));
        args.addAll(command.getKeys().stream().map(v -> toByteArray(v)).collect(Collectors.toList()));

        Mono<Long> m = write((byte[])args.get(0), StringCodec.INSTANCE, RedisCommands.SDIFFSTORE, args.toArray());
        return m.map(v -> new NumericResponse<>(command, v));
    });
}
 
Example #17
Source Project: resilience4j   Author: resilience4j   File: FluxRateLimiter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(CoreSubscriber<? super T> actual) {
    long waitDuration = rateLimiter.reservePermission();
    if (waitDuration >= 0) {
        if (waitDuration > 0) {
            Mono.delay(Duration.ofNanos(waitDuration))
                .subscribe(delay -> source.subscribe(new RateLimiterSubscriber<>(actual)));
        } else {
            source.subscribe(new RateLimiterSubscriber<>(actual));
        }
    } else {
        Operators.error(actual, createRequestNotPermitted(rateLimiter));
    }
}
 
Example #18
Source Project: charon-spring-boot-starter   Author: mkopylec   File: Retryer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Mono<HttpResponse> forward(HttpRequest request, HttpRequestExecution execution) {
    logStart(execution.getMappingName());
    Retry retry = getRegistry().retry(execution.getMappingName());
    setupMetrics(registry -> createMetrics(registry, execution.getMappingName()));
    return execution.execute(request)
            .transform(of(retry))
            .doOnSuccess(response -> logEnd(execution.getMappingName()));
}
 
Example #19
Source Project: spring-analysis-note   Author: Vip-Augus   File: MessageHandlerAcceptor.java    License: 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 #20
Source Project: spring-analysis-note   Author: Vip-Augus   File: HttpHeadResponseDecorator.java    License: 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 #21
Source Project: charon-spring-boot-starter   Author: mkopylec   File: RegexRequestPathRewriter.java    License: 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 #22
Source Project: reactor-pool   Author: reactor   File: CommonPoolTest.java    License: 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 #23
Source Project: james-project   Author: apache   File: UserMailboxesService.java    License: 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 #24
Source Project: Spring-5.0-By-Example   Author: PacktPublishing   File: DiscoveryService.java    License: 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 #25
Source Project: linstor-server   Author: LINBIT   File: FreeCapacityFetcherProto.java    License: 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 #26
Source Project: james-project   Author: apache   File: MessageFastViewProjectionContract.java    License: 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 #27
Source Project: james-project   Author: apache   File: CassandraEventDeadLetters.java    License: 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 #28
Source Project: crnk-framework   Author: crnk-project   File: MonoResultFactory.java    License: Apache License 2.0 5 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 #29
Source Project: spring-analysis-note   Author: Vip-Augus   File: AbstractReactiveTransactionAspectTests.java    License: 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 #30
Source Project: open-cloud   Author: liuyadu   File: JdbcRouteDefinitionLocator.java    License: MIT License 5 votes vote down vote up
/**
 * 刷新路由
 *
 * @return
 */
public Mono<Void> refresh() {
    this.loadRoutes();
    // 触发默认路由刷新事件,刷新缓存路由
    this.publisher.publishEvent(new RefreshRoutesEvent(this));
    return Mono.empty();
}