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

The following examples show how to use reactor.core.publisher.Mono#zip() . 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
/**
 * Executes all sanitizers in parallel, collecting partial results in the first phase, and applying them all
 * sequentially through each sanitizer in the second phase.
 * <p>
 * The iteration order of the sanitizers is not guaranteed. Any sanitization failure results in the Mono
 * emitting an error.
 *
 * @return a {@link Function} that applies partial updates through all sanitizers sequentially
 */
public Mono<UnaryOperator<JobDescriptor>> sanitize(JobDescriptor entity) {
    List<Mono<UnaryOperator<JobDescriptor>>> sanitizationFunctions = sanitizers.stream()
            .map(s -> s.sanitize(entity)
                    .subscribeOn(Schedulers.parallel())
                    .timeout(getTimeout(), Mono.error(() -> TitusServiceException.internal(
                            s.getClass().getSimpleName() + " timed out running job sanitization")
                    ))
                    // important: Mono.zip will be short circuited if members are empty
                    .switchIfEmpty(Mono.just(UnaryOperator.identity()))
            )
            .collect(Collectors.toList());

    Mono<UnaryOperator<JobDescriptor>> merged = Mono.zip(sanitizationFunctions, partials -> {
        if (CollectionsExt.isNullOrEmpty(partials)) {
            return UnaryOperator.identity();
        }
        //noinspection unchecked
        return applyAll(Arrays.stream(partials).map(partial -> (UnaryOperator<JobDescriptor>) partial));
    });

    return merged.switchIfEmpty(Mono.just(UnaryOperator.identity()))
            .timeout(getTimeout().multipliedBy(2),
                    Mono.error(() -> TitusServiceException.internal("Job sanitization timed out")));

}
 
Example 2
@Override
public int getRunningTaskExecutionCount() {

	Mono<Tuple2<String,String>> orgAndSpace = Mono.zip(organizationId, spaceId);

	Mono<ListTasksRequest> listTasksRequest = orgAndSpace.map(tuple->
			ListTasksRequest.builder()
			.state(TaskState.RUNNING)
			.organizationId(tuple.getT1())
			.spaceId(tuple.getT2())
			.build());

	return listTasksRequest.flatMap(request-> this.client.tasks().list(request))
			.map(listTasksResponse -> listTasksResponse.getPagination().getTotalResults())
			.doOnError(logError("Failed to list running tasks"))
			.doOnSuccess(count -> logger.info(String.format("There are %d running tasks", count)))
			.block(Duration.ofMillis(this.deploymentProperties.getStatusTimeout()));
}
 
Example 3
@Override
public Mono<PermissionSet> getEffectivePermissions(Snowflake memberId) {
    Mono<Member> getMember = getClient().getMemberById(getGuildId(), memberId);
    Mono<PermissionSet> getBasePerms = getMember.flatMap(Member::getBasePermissions);

    return Mono.zip(getMember, getBasePerms, (member, basePerms) -> {
        PermissionOverwrite everyoneOverwrite = getOverwriteForRole(getGuildId()).orElse(null);

        List<PermissionOverwrite> roleOverwrites = member.getRoleIds().stream()
                .map(this::getOverwriteForRole)
                .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)) // jdk 9 Optional#stream
                .collect(Collectors.toList());
        PermissionOverwrite memberOverwrite = getOverwriteForMember(member.getId()).orElse(null);

        return PermissionUtil.computePermissions(basePerms, everyoneOverwrite, roleOverwrites, memberOverwrite);
    });
}
 
Example 4
@GetMapping("/{id}")
@QueryAction
public Mono<GatewayDeviceInfo> getGatewayInfo(@PathVariable String id) {
    return Mono.zip(
        instanceService.findById(id),
        instanceService.createQuery()
            .where()
            .is(DeviceInstanceEntity::getParentId, id)
            .fetch()
            .collectList()
            .defaultIfEmpty(Collections.emptyList()),
        GatewayDeviceInfo::of);
}
 
Example 5
private Mono<Object[]> getMethodArgumentValues(
		ServerWebExchange exchange, BindingContext bindingContext, Object... providedArgs) {

	if (ObjectUtils.isEmpty(getMethodParameters())) {
		return EMPTY_ARGS;
	}
	MethodParameter[] parameters = getMethodParameters();
	List<Mono<Object>> argMonos = new ArrayList<>(parameters.length);
	for (MethodParameter parameter : parameters) {
		parameter.initParameterNameDiscovery(this.parameterNameDiscoverer);
		Object providedArg = findProvidedArgument(parameter, providedArgs);
		if (providedArg != null) {
			argMonos.add(Mono.just(providedArg));
			continue;
		}
		if (!this.resolvers.supportsParameter(parameter)) {
			return Mono.error(new IllegalStateException(
					formatArgumentError(parameter, "No suitable resolver")));
		}
		try {
			argMonos.add(this.resolvers.resolveArgument(parameter, bindingContext, exchange)
					.defaultIfEmpty(NO_ARG_VALUE)
					.doOnError(cause -> logArgumentErrorIfNecessary(exchange, parameter, cause)));
		}
		catch (Exception ex) {
			logArgumentErrorIfNecessary(exchange, parameter, ex);
			argMonos.add(Mono.error(ex));
		}
	}
	return Mono.zip(argMonos, values ->
			Stream.of(values).map(o -> o != NO_ARG_VALUE ? o : null).toArray());
}
 
Example 6
@Test
public void realLifeMono() throws Exception {
	//given
	final Mono<Order> order = UserOrders.lastOrderOf(new User(20));
	final Mono<Boolean> ping = Ping.checkConstantly("example.com").next();

	//when
	final Mono<Tuple2<Order, Boolean>> result = Mono.zip(
			order,
			ping
	);
}
 
Example 7
@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 8
private static Mono<Tuple2<Relic, Optional<Guild>>> getRelicAndGuild(Context context, Relic relic) {
    final Mono<Optional<Guild>> getGuild = Mono.justOrEmpty(relic.getGuildId())
            .flatMap(context.getClient()::getGuildById)
            .map(Optional::of)
            .defaultIfEmpty(Optional.empty());

    return Mono.zip(Mono.just(relic), getGuild);
}
 
Example 9
public Mono<BookDto> toBookDto(Book book) {
  BookDto bookDto = bookMapper.toBookDto(book);
  return Mono.zip(
      authorRepository.findByBook(book.getId()).collectList().map(bookMapper::toAuthorDtos),
      categoryRepository.findByBook(book.getId()).collectList().map(bookMapper::toCategoryDtos),
      (authorDtos, categorieDtos) -> {
        bookDto.setAuthors(authorDtos);
        bookDto.setCategories(categorieDtos);
        return bookDto;
      });
}
 
Example 10
Source Project: reactor-netty   File: HttpClientTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testIssue777() {
	disposableServer = HttpServer.create()
	                             .port(0)
	                             .wiretap(true)
	                             .route(r ->
	                                 r.post("/empty", (req, res) -> {
	                                     // Just consume the incoming body
	                                     req.receive().subscribe();
	                                     return res.status(400)
	                                               .header(HttpHeaderNames.CONNECTION, "close")
	                                               .send(Mono.empty());
	                                  })
	                                  .post("/test", (req, res) -> {
	                                      // Just consume the incoming body
	                                      req.receive().subscribe();
	                                      return res.status(400)
	                                                .header(HttpHeaderNames.CONNECTION, "close")
	                                                .sendString(Mono.just("Test"));
	                                  }))
	                             .bindNow();

	HttpClient client = createHttpClientForContextWithAddress();

	BiFunction<HttpClientResponse, ByteBufMono, Mono<String>> receiver =
			(resp, bytes) -> {
				if (!Objects.equals(HttpResponseStatus.OK, resp.status())) {
					return bytes.asString()
					            .switchIfEmpty(Mono.just(resp.status().reasonPhrase()))
					            .flatMap(text -> Mono.error(new RuntimeException(text)));
				}
				return bytes.asString();
			};
	doTestIssue777_1(client, "/empty", "Bad Request", receiver);
	doTestIssue777_1(client, "/test", "Test", receiver);

	receiver = (resp, bytes) -> {
		if (Objects.equals(HttpResponseStatus.OK, resp.status())) {
			return bytes.asString();
		}
		return Mono.error(new RuntimeException("error"));
	};
	doTestIssue777_1(client, "/empty", "error", receiver);
	doTestIssue777_1(client, "/test", "error", receiver);

	BiFunction<HttpClientResponse, ByteBufMono, Mono<Tuple2<String, HttpClientResponse>>> receiver1 =
			(resp, byteBuf) ->
					Mono.zip(byteBuf.asString(StandardCharsets.UTF_8)
					                .switchIfEmpty(Mono.just(resp.status().reasonPhrase())),
					         Mono.just(resp));
	doTestIssue777_2(client, "/empty", "Bad Request", receiver1);
	doTestIssue777_2(client, "/test", "Test", receiver1);

	receiver =
			(resp, bytes) -> bytes.asString(StandardCharsets.UTF_8)
			                      .switchIfEmpty(Mono.just(resp.status().reasonPhrase()))
			                      .map(respBody -> {
			                          if (!Objects.equals(HttpResponseStatus.OK, resp.status())) {
			                              throw new RuntimeException(respBody);
			                          }
			                          return respBody;
			                      });
	doTestIssue777_1(client, "/empty", "Bad Request", receiver);
	doTestIssue777_1(client, "/test", "Test", receiver);
}
 
Example 11
Source Project: tutorials   File: Client.java    License: MIT License 4 votes vote down vote up
public Mono<UserWithItem> fetchUserAndItem(int userId, int itemId) {
    Mono<User> user = getUser(userId).subscribeOn(Schedulers.elastic());
    Mono<Item> item = getItem(itemId).subscribeOn(Schedulers.elastic());

    return Mono.zip(user, item, UserWithItem::new);
}
 
Example 12
/**
 * 分页查询并转换数据
 *
 * @param queryParam 查询参数
 * @param mapper     转换规则
 * @param <T>        结果类型
 * @return 查询结果
 */
default <T> Mono<PagerResult<T>> queryPager(QueryParam queryParam, Function<TimeSeriesData, T> mapper) {
    return Mono.zip(
        count(queryParam),
        query(queryParam).map(mapper).collectList(),
        (total, data) -> PagerResult.of(total, data, queryParam));
}