io.vavr.API类的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(12.5k)|赞(0)|评价(0)|浏览(114)

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

API介绍

[英]The most basic Vavr functionality is accessed through this API class.

import static io.vavr.API.*;

For-comprehension

The For-comprehension is syntactic sugar for nested for-loops. We write

// lazily evaluated 
Iterator<R> result = For(iterable1, iterable2, ..., iterableN).yield(f);

or

Iterator<R> result = 
For(iterable1, v1 -> 
For(iterable2, v2 -> 
... 
For(iterableN).yield(vN -> f.apply(v1, v2, ..., vN)) 
) 
);

instead of

for(T1 v1 : iterable1) { 
for (T2 v2 : iterable2) { 
... 
for (TN vN : iterableN) { 
R result = f.apply(v1, v2, ..., VN); 
// 
// We are forced to perform side effects to do s.th. meaningful with the result. 
// 
} 
} 
}

Please note that values like Option, Try, Future, etc. are also iterable.

Given a suitable function f: (v1, v2, ..., vN) -> ... and 1 <= N <= 8 iterables, the result is a Stream of the mapped cross product elements.

{ f(v1, v2, ..., vN) | v1 ∈ iterable1, ... vN ∈ iterableN }

As with all Vavr Values, the result of a For-comprehension can be converted to standard Java library and Vavr types.
[中]最基本的Vavr功能是通过该API类访问的

import static io.vavr.API.*;

####为了理解
理解的关键是嵌套For循环的语法糖。我们写
<

// lazily evaluated 
Iterator<R> result = For(iterable1, iterable2, ..., iterableN).yield(f);

Iterator<R> result = 
For(iterable1, v1 -> 
For(iterable2, v2 -> 
... 
For(iterableN).yield(vN -> f.apply(v1, v2, ..., vN)) 
) 
);

而不是

for(T1 v1 : iterable1) { 
for (T2 v2 : iterable2) { 
... 
for (TN vN : iterableN) { 
R result = f.apply(v1, v2, ..., VN); 
// 
// We are forced to perform side effects to do s.th. meaningful with the result. 
// 
} 
} 
}

请注意,选项、尝试、未来等值也是可计算的。
给定一个合适的函数f:(v1,v2,…,vN)->。。。和1<=N<=8个可数,结果是映射的叉积元素流。

{ f(v1, v2, ..., vN) | v1 ∈ iterable1, ... vN ∈ iterableN }

与所有Vavr值一样,可将理解的结果转换为标准Java库和Vavr类型。

代码示例

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldConsumeIgnoredErrorEvent() {
  CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
      .recordFailure(throwable -> Match(throwable).of(
          Case($(instanceOf(WebServiceException.class)), true),
          Case($(), false)))
      .build();
  circuitBreaker = CircuitBreaker.of("test", circuitBreakerConfig);
  circuitBreaker.getEventPublisher()
      .onIgnoredError(this::logEventType)
  ;
  circuitBreaker.onError(1000, new IOException("BAM!"));
  then(logger).should(times(1)).info("IGNORED_ERROR");
}

代码示例来源:origin: jenkinsci/configuration-as-code-plugin

private static Optional<String> reveal(ConfigurationContext context, String captured) {
  return context.getSecretSources().stream()
      .map(source -> unchecked(() -> source.reveal(captured)).apply())
      .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
      .findFirst();
}

代码示例来源:origin: jenkinsci/configuration-as-code-plugin

private GeneratedItems generateFromScript(String script, JenkinsJobManagement management) {
  return unchecked(() ->
      Try(() -> new JenkinsDslScriptLoader(management).runScript(script))
          .getOrElseThrow(t -> new ConfiguratorException(this, "Failed to execute script with hash " + script.hashCode(), t))).apply();
}

代码示例来源:origin: vavr-io/vavr

/**
 * Maps the cause to a new exception if this is a {@code Failure} or returns this instance if this is a {@code Success}.
 * <p>
 * If none of the given cases matches the cause, the same {@code Failure} is returned.
 *
 * @param cases A not necessarily exhaustive sequence of cases that will be matched against a cause.
 * @return A new {@code Try} if this is a {@code Failure}, otherwise this.
 */
@GwtIncompatible
@SuppressWarnings({ "unchecked", "varargs" })
default Try<T> mapFailure(Match.Case<? extends Throwable, ? extends Throwable>... cases) {
  if (isSuccess()) {
    return this;
  } else {
    final Option<Throwable> x = Match(getCause()).option(cases);
    return x.isEmpty() ? this : failure(x.get());
  }
}

代码示例来源:origin: net.serenity-bdd/serenity-screenplay

ErrorTally(EventBusInterface eventBusInterface) {
  this.eventBusInterface = eventBusInterface;
  this.errors = List();
}

代码示例来源:origin: io.vavr/vavr

/**
 * Maps the cause to a new exception if this is a {@code Failure} or returns this instance if this is a {@code Success}.
 * <p>
 * If none of the given cases matches the cause, the same {@code Failure} is returned.
 *
 * @param cases A not necessarily exhaustive sequence of cases that will be matched against a cause.
 * @return A new {@code Try} if this is a {@code Failure}, otherwise this.
 */
@GwtIncompatible
@SuppressWarnings({ "unchecked", "varargs" })
default Try<T> mapFailure(Match.Case<? extends Throwable, ? extends Throwable>... cases) {
  if (isSuccess()) {
    return this;
  } else {
    final Option<Throwable> x = Match(getCause()).option(cases);
    return x.isEmpty() ? this : failure(x.get());
  }
}

代码示例来源:origin: jenkinsci/configuration-as-code-plugin

private String getScriptFromSource(CNode source, ConfigurationContext context, Configurator<ScriptSource> configurator) {
    return unchecked(() ->
        Try(() -> configurator.configure(source, context))
            .getOrElseThrow(t -> new ConfiguratorException(this, "Failed to retrieve job-dsl script", t))
            .getScript()).apply();
  }
}

代码示例来源:origin: net.serenity-bdd/serenity-model

private static List<String> convertArguments(Object[] arguments) {
  return List(arguments).map(StepArgumentWriter::readableFormOf).asJava();
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void waitForPermissionWithInterruption() throws Exception {
  when(limit.getPermission(config.getTimeoutDuration()))
    .then(invocation -> {
      LockSupport.parkNanos(5_000_000_000L);
      return null;
    });
  AtomicBoolean wasInterrupted = new AtomicBoolean(true);
  Thread thread = new Thread(() -> {
    wasInterrupted.set(false);
    Throwable cause = Try.run(() -> RateLimiter.waitForPermission(limit))
      .getCause();
    Boolean interrupted = Match(cause).of(
      Case($(instanceOf(IllegalStateException.class)), true)
    );
    wasInterrupted.set(interrupted);
  });
  thread.setDaemon(true);
  thread.start();
  await()
    .atMost(5, TimeUnit.SECONDS)
    .until(wasInterrupted::get, equalTo(false));
  thread.interrupt();
  await()
    .atMost(5, TimeUnit.SECONDS)
    .until(wasInterrupted::get, equalTo(true));
}

代码示例来源:origin: jenkinsci/configuration-as-code-plugin

private CNode getActualValue(CNode config, ConfigurationContext context) {
  return unchecked(() -> config.asMapping().entrySet().stream().findFirst()).apply()
      .map(entry -> {
        Mapping mapping = new Mapping();
        mapping.put(entry.getKey(), revealSourceOrGetValue(entry, context));
        return (CNode) mapping;
      }).orElse(config);
}

代码示例来源:origin: net.serenity-bdd/serenity-model

private Map<String, List<TestOutcome>> groupByTestCase(TestOutcomes testOutcomes) {
  Map<String, List<TestOutcome>> groupedTestOutcomes = new HashMap<>();
  for (TestOutcome outcome : testOutcomes.getOutcomes()) {
    String testCaseName = StringUtils.isNotEmpty(outcome.getTestCaseName()) ? outcome.getTestCaseName() : outcome.getStoryTitle();
    List<TestOutcome> currentOutcomes = groupedTestOutcomes.getOrDefault(testCaseName, List());
    groupedTestOutcomes.put(testCaseName, currentOutcomes.append(outcome));
  }
  return groupedTestOutcomes;
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldReturnAfterOneAttemptAndIgnoreException() {
  // Given the HelloWorldService throws an exception
  BDDMockito.given(helloWorldService.returnHelloWorld()).willThrow(new WebServiceException("BAM!"));
  // Create a Retry with default configuration
  RetryConfig config = RetryConfig.custom()
      .retryOnException(throwable -> API.Match(throwable).of(
          API.Case($(Predicates.instanceOf(WebServiceException.class)), false),
          API.Case($(), true)))
      .build();
  Retry retry = Retry.of("id", config);
  // Decorate the invocation of the HelloWorldService
  CheckedFunction0<String> retryableSupplier = Retry
      .decorateCheckedSupplier(retry, helloWorldService::returnHelloWorld);
  // When
  Try<String> result = Try.of(retryableSupplier);
  // Then the helloWorldService should be invoked only once, because the exception should be rethrown immediately.
  BDDMockito.then(helloWorldService).should(Mockito.times(1)).returnHelloWorld();
  // and the result should be a failure
  assertThat(result.isFailure()).isTrue();
  // and the returned exception should be of type RuntimeException
  assertThat(result.failed().get()).isInstanceOf(WebServiceException.class);
  assertThat(sleptTime).isEqualTo(0);
}

代码示例来源:origin: jenkinsci/configuration-as-code-plugin

private String revealSourceOrGetValue(Map.Entry<String, CNode> entry, ConfigurationContext context) {
  String value = unchecked(() -> entry.getValue().asScalar().getValue()).apply();
  return SecretSourceResolver.resolve(context, value);
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldReturnAfterOneAttemptAndIgnoreException() {
  // Given the HelloWorldService throws an exception
  BDDMockito.willThrow(new WebServiceException("BAM!")).given(helloWorldService).sayHelloWorld();
  // Create a Retry with default configuration
  RetryConfig config = RetryConfig.custom()
      .retryOnException(throwable -> Match(throwable).of(
          Case($(Predicates.instanceOf(WebServiceException.class)), false),
          Case($(), true)))
      .build();
  Retry retry = Retry.of("id", config);
  // Decorate the invocation of the HelloWorldService
  CheckedRunnable retryableRunnable = Retry.decorateCheckedRunnable(retry, helloWorldService::sayHelloWorld);
  // When
  Try<Void> result = Try.run(retryableRunnable);
  // Then the helloWorldService should be invoked only once, because the exception should be rethrown immediately.
  BDDMockito.then(helloWorldService).should(Mockito.times(1)).sayHelloWorld();
  // and the result should be a failure
  Assertions.assertThat(result.isFailure()).isTrue();
  // and the returned exception should be of type RuntimeException
  Assertions.assertThat(result.failed().get()).isInstanceOf(WebServiceException.class);
  Assertions.assertThat(sleptTime).isEqualTo(0);
}

代码示例来源:origin: Tristan971/Lyrebird

@Cacheable("availableVersions")
public List<LyrebirdVersion> getAllVersions() {
  final PathMatchingResourcePatternResolver versionsResourcesResolver = new PathMatchingResourcePatternResolver();
  try {
    final Resource[] versionResources = versionsResourcesResolver.getResources(VERSIONS_PATTERN);
    return Arrays.stream(versionResources)
           .map(unchecked(Resource::getInputStream))
           .map(unchecked(is -> objectMapper.readValue(is, LyrebirdVersion.class)))
           .sorted(Comparator.comparing(LyrebirdVersion::getBuildVersion).reversed())
           .collect(Collectors.toList());
  } catch (final IOException e) {
    throw new IllegalStateException("Can not load releases!", e);
  }
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldConsumeIgnoredErrorEvent() {
  given(helloWorldService.returnHelloWorld())
      .willThrow(new WebServiceException("BAM!"));
  RetryConfig retryConfig = RetryConfig.custom()
      .retryOnException(throwable -> Match(throwable).of(
          Case($(instanceOf(WebServiceException.class)), false),
          Case($(), true)))
      .build();
  retry = Retry.of("testName", retryConfig);
  retry.getEventPublisher()
    .onIgnoredError(event ->
        logger.info(event.getEventType().toString()));
  Try.ofSupplier(Retry.decorateSupplier(retry, helloWorldService::returnHelloWorld));
  then(logger).should(times(1)).info("IGNORED_ERROR");
  then(helloWorldService).should(times(1)).returnHelloWorld();
}

代码示例来源:origin: Tristan971/Lyrebird

/**
 * Uploads the given media files to Twitter
 *
 * @param twitter     The twitter instance to use for uploading
 * @param attachments The media files to upload
 *
 * @return The uploaded media files Twitter-side ids
 */
private static List<Long> uploadMedias(final Twitter twitter, final List<File> attachments) {
  LOG.debug("Uploading media attachments {}", attachments);
  return attachments.stream()
           .map(unchecked((CheckedFunction1<File, UploadedMedia>) twitter::uploadMedia))
           .map(UploadedMedia::getMediaId)
           .collect(Collectors.toList());
}

代码示例来源:origin: resilience4j/resilience4j

.ringBufferSizeInHalfOpenState(2)
    .waitDurationInOpenState(Duration.ofMillis(1000))
    .recordFailure(throwable -> Match(throwable).of(
        Case($(instanceOf(WebServiceException.class)), true),
        Case($(), false)))
    .build();
CircuitBreaker circuitBreaker = CircuitBreaker.of("testName", circuitBreakerConfig);

代码示例来源:origin: io.jenkins/configuration-as-code

private static Optional<String> reveal(ConfigurationContext context, String captured) {
  return context.getSecretSources().stream()
      .map(source -> unchecked(() -> source.reveal(captured)).apply())
      .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
      .findFirst();
}

代码示例来源:origin: resilience4j/resilience4j

@Test
public void shouldConsumeIgnoredErrorEvent() {
  given(helloWorldService.returnHelloWorld())
      .willThrow(new WebServiceException("BAM!"));
  RetryConfig retryConfig = RetryConfig.custom()
      .retryOnException(throwable -> Match(throwable).of(
          Case($(instanceOf(WebServiceException.class)), false),
          Case($(), true)))
      .build();
  retry = AsyncRetry.of("testName", retryConfig);
  retry.getEventPublisher()
    .onIgnoredError(event ->
        logger.info(event.getEventType().toString()));
  Try.of(() -> awaitResult(retry.executeCompletionStage(scheduler,
      () -> helloWorldService.returnHelloWorld())));
  then(logger).should(times(1)).info("IGNORED_ERROR");
  then(helloWorldService).should(times(1)).returnHelloWorld();
}

相关文章

微信公众号

最新文章

更多