reactor.core.publisher.Mono.defaultIfEmpty()方法的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(9.5k)|赞(0)|评价(0)|浏览(968)

本文整理了Java中reactor.core.publisher.Mono.defaultIfEmpty()方法的一些代码示例,展示了Mono.defaultIfEmpty()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Mono.defaultIfEmpty()方法的具体详情如下:
包路径:reactor.core.publisher.Mono
类名称:Mono
方法名:defaultIfEmpty

Mono.defaultIfEmpty介绍

[英]Provide a default single value if this mono is completed without any data
[中]如果此mono在没有任何数据的情况下完成,请提供默认的单个值

代码示例

代码示例来源:origin: spring-projects/spring-framework

@Nullable
private String formatBody(@Nullable MediaType contentType, Mono<byte[]> body) {
  return body
      .map(bytes -> {
        if (contentType == null) {
          return bytes.length + " bytes of content (unknown content-type).";
        }
        Charset charset = contentType.getCharset();
        if (charset != null) {
          return new String(bytes, charset);
        }
        if (PRINTABLE_MEDIA_TYPES.stream().anyMatch(contentType::isCompatibleWith)) {
          return new String(bytes, StandardCharsets.UTF_8);
        }
        return bytes.length + " bytes of content.";
      })
      .defaultIfEmpty("No content")
      .onErrorResume(ex -> Mono.just("Failed to obtain content: " + ex.getMessage()))
      .block(this.timeout);
}

代码示例来源:origin: spring-projects/spring-security

private Mono<Authentication> currentAuthentication() {
  return ReactiveSecurityContextHolder.getContext()
      .map(SecurityContext::getAuthentication)
      .defaultIfEmpty(ANONYMOUS_USER_TOKEN);
}

代码示例来源:origin: spring-projects/spring-security

private Mono<Authentication> currentAuthentication() {
  return ReactiveSecurityContextHolder.getContext()
      .map(SecurityContext::getAuthentication)
      .defaultIfEmpty(ANONYMOUS_USER_TOKEN);
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public Mono<Object> resolveArgument(
    MethodParameter parameter, BindingContext bindingContext, ServerWebExchange exchange) {
  Class<?> entityType = parameter.getParameterType();
  return readBody(parameter.nested(), parameter, false, bindingContext, exchange)
      .map(body -> createEntity(body, entityType, exchange.getRequest()))
      .defaultIfEmpty(createEntity(null, entityType, exchange.getRequest()));
}

代码示例来源:origin: codecentric/spring-boot-admin

/**
 * Get a single instance.
 *
 * @param id The application identifier.
 * @return The registered application.
 */
@GetMapping(path = "/instances/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public Mono<ResponseEntity<Instance>> instance(@PathVariable String id) {
  LOGGER.debug("Deliver registered instance with ID '{}'", id);
  return registry.getInstance(InstanceId.of(id))
          .filter(Instance::isRegistered)
          .map(ResponseEntity::ok)
          .defaultIfEmpty(ResponseEntity.notFound().build());
}

代码示例来源:origin: codecentric/spring-boot-admin

/**
 * Unregister an instance
 *
 * @param id The instance id.
 * @return response indicating the success
 */
@DeleteMapping(path = "/instances/{id}")
public Mono<ResponseEntity<Void>> unregister(@PathVariable String id) {
  LOGGER.debug("Unregister instance with ID '{}'", id);
  return registry.deregister(InstanceId.of(id))
          .map(v -> ResponseEntity.noContent().<Void>build())
          .defaultIfEmpty(ResponseEntity.notFound().build());
}

代码示例来源:origin: spring-projects/spring-security

@Override
public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, T object) {
  return authentication
    .filter(a -> a.isAuthenticated())
    .flatMapIterable( a -> a.getAuthorities())
    .map(g -> g.getAuthority())
    .any(a -> this.authorities.contains(a))
    .map( hasAuthority -> new AuthorizationDecision(hasAuthority))
    .defaultIfEmpty(new AuthorizationDecision(false));
}

代码示例来源:origin: spring-projects/spring-framework

private Mono<? extends Resource> transformContent(String cssContent, Resource resource,
    ResourceTransformerChain chain, ServerWebExchange exchange) {
  List<ContentChunkInfo> contentChunkInfos = parseContent(cssContent);
  if (contentChunkInfos.isEmpty()) {
    return Mono.just(resource);
  }
  return Flux.fromIterable(contentChunkInfos)
      .concatMap(contentChunkInfo -> {
        String contentChunk = contentChunkInfo.getContent(cssContent);
        if (contentChunkInfo.isLink() && !hasScheme(contentChunk)) {
          String link = toAbsolutePath(contentChunk, exchange);
          return resolveUrlPath(link, exchange, resource, chain).defaultIfEmpty(contentChunk);
        }
        else {
          return Mono.just(contentChunk);
        }
      })
      .reduce(new StringWriter(), (writer, chunk) -> {
        writer.write(chunk);
        return writer;
      })
      .map(writer -> {
        byte[] newContent = writer.toString().getBytes(DEFAULT_CHARSET);
        return new TransformedResource(resource, newContent);
      });
}

代码示例来源:origin: codecentric/spring-boot-admin

@GetMapping(path = "/applications/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
public Mono<ResponseEntity<Application>> application(@PathVariable("name") String name) {
  return this.toApplication(name, registry.getInstances(name).filter(Instance::isRegistered))
        .filter(a -> !a.getInstances().isEmpty())
        .map(ResponseEntity::ok)
        .defaultIfEmpty(ResponseEntity.notFound().build());
}

代码示例来源:origin: spring-projects/spring-framework

.defaultIfEmpty(NO_ARG_VALUE)
.doOnError(cause -> logArgumentErrorIfNecessary(exchange, parameter, cause)));

代码示例来源:origin: spring-projects/spring-security

@Override
public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, T object) {
  return authentication
    .filter(this::isNotAnonymous)
    .map(a -> new AuthorizationDecision(a.isAuthenticated()))
    .defaultIfEmpty(new AuthorizationDecision(false));
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Convert the given {@linkplain RouterFunction router function} into a {@link WebHandler},
 * using the given strategies.
 * @param routerFunction the router function to convert
 * @param strategies the strategies to use
 * @return a web handler that handles web request using the given router function
 */
public static WebHandler toWebHandler(RouterFunction<?> routerFunction, HandlerStrategies strategies) {
  Assert.notNull(routerFunction, "RouterFunction must not be null");
  Assert.notNull(strategies, "HandlerStrategies must not be null");
  return exchange -> {
    ServerRequest request = new DefaultServerRequest(exchange, strategies.messageReaders());
    addAttributes(exchange, request);
    return routerFunction.route(request)
        .defaultIfEmpty(notFound())
        .flatMap(handlerFunction -> wrapException(() -> handlerFunction.handle(request)))
        .flatMap(response -> wrapException(() -> response.writeTo(exchange,
            new HandlerStrategiesResponseContext(strategies))));
  };
}

代码示例来源:origin: codecentric/spring-boot-admin

protected Mono<Info> convertInfo(Instance instance, ClientResponse response) {
  if (response.statusCode().is2xxSuccessful() &&
    response.headers()
        .contentType()
        .map(mt -> mt.isCompatibleWith(MediaType.APPLICATION_JSON) ||
              mt.isCompatibleWith(ACTUATOR_V2_MEDIATYPE))
        .orElse(false)) {
    return response.bodyToMono(RESPONSE_TYPE).map(Info::from).defaultIfEmpty(Info.empty());
  }
  log.info("Couldn't retrieve info for {}: {}", instance, response.statusCode());
  return response.bodyToMono(Void.class).then(Mono.just(Info.empty()));
}

代码示例来源:origin: codecentric/spring-boot-admin

protected Mono<StatusInfo> convertStatusInfo(ClientResponse response) {
  Boolean hasCompatibleContentType = response.headers()
                        .contentType()
                        .map(mt -> mt.isCompatibleWith(MediaType.APPLICATION_JSON) ||
                             mt.isCompatibleWith(ACTUATOR_V2_MEDIATYPE))
                        .orElse(false);
  StatusInfo statusInfoFromStatus = this.getStatusInfoFromStatus(response.statusCode(), emptyMap());
  if (hasCompatibleContentType) {
    return response.bodyToMono(RESPONSE_TYPE).map(body -> {
      if (body.get("status") instanceof String) {
        return StatusInfo.from(body);
      }
      return getStatusInfoFromStatus(response.statusCode(), body);
    }).defaultIfEmpty(statusInfoFromStatus);
  }
  return response.bodyToMono(Void.class).then(Mono.just(statusInfoFromStatus));
}

代码示例来源:origin: spring-projects/spring-security

Mono<Request> createDefaultedRequest(String clientRegistrationId,
    Authentication authentication, ServerWebExchange exchange) {
  Mono<Authentication> defaultedAuthentication = Mono.justOrEmpty(authentication)
      .switchIfEmpty(currentAuthentication());
  Mono<String> defaultedRegistrationId = Mono.justOrEmpty(clientRegistrationId)
      .switchIfEmpty(Mono.justOrEmpty(this.defaultClientRegistrationId))
      .switchIfEmpty(clientRegistrationId(defaultedAuthentication));
  Mono<Optional<ServerWebExchange>> defaultedExchange = Mono.justOrEmpty(exchange)
      .switchIfEmpty(currentServerWebExchange()).map(Optional::of)
      .defaultIfEmpty(Optional.empty());
  return Mono.zip(defaultedRegistrationId, defaultedAuthentication, defaultedExchange)
      .map(t3 -> new Request(t3.getT1(), t3.getT2(), t3.getT3().orElse(null)));
}

代码示例来源:origin: spring-projects/spring-framework

return bytes;
})
.defaultIfEmpty(new byte[0])
.map(bodyBytes -> {
  Charset charset = response.headers().contentType()

代码示例来源:origin: reactor/reactor-core

@Test
public void errorHide() {
  StepVerifier.create(Mono.error(new RuntimeException("forced failure"))
              .hide()
              .defaultIfEmpty("blah"))
        .verifyErrorMessage("forced failure");
}

代码示例来源:origin: reactor/reactor-core

@Test
public void nonEmptyHide() {
  AssertSubscriber<Integer> ts = AssertSubscriber.create();
  Mono.just(1).hide().defaultIfEmpty(10).subscribe(ts);
  ts.assertValues(1)
   .assertComplete()
   .assertNoError();
}

代码示例来源:origin: reactor/reactor-core

@Test
public void nonEmptyBackpressured() {
  AssertSubscriber<Integer> ts = AssertSubscriber.create(0);
  Mono.just(1).defaultIfEmpty(10).subscribe(ts);
  ts.assertNoValues()
   .assertNoError()
   .assertNotComplete();
  ts.request(2);
  ts.assertValues(1)
   .assertComplete()
   .assertNoError();
}

代码示例来源:origin: reactor/reactor-core

@Test
public void emptyBackpressured() {
  AssertSubscriber<Integer> ts = AssertSubscriber.create(0);
  Mono.<Integer>empty().defaultIfEmpty(10).subscribe(ts);
  ts.assertNoValues()
   .assertNoError()
   .assertNotComplete();
  ts.request(2);
  ts.assertValues(10)
   .assertComplete()
   .assertNoError();
}

相关文章

Mono类方法