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

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

本文整理了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.

  1. import static io.vavr.API.*;

For-comprehension

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

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

or

  1. Iterator<R> result =
  2. For(iterable1, v1 ->
  3. For(iterable2, v2 ->
  4. ...
  5. For(iterableN).yield(vN -> f.apply(v1, v2, ..., vN))
  6. )
  7. );

instead of

  1. for(T1 v1 : iterable1) {
  2. for (T2 v2 : iterable2) {
  3. ...
  4. for (TN vN : iterableN) {
  5. R result = f.apply(v1, v2, ..., VN);
  6. //
  7. // We are forced to perform side effects to do s.th. meaningful with the result.
  8. //
  9. }
  10. }
  11. }

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.

  1. { 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类访问的

  1. import static io.vavr.API.*;

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

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

  1. Iterator<R> result =
  2. For(iterable1, v1 ->
  3. For(iterable2, v2 ->
  4. ...
  5. For(iterableN).yield(vN -> f.apply(v1, v2, ..., vN))
  6. )
  7. );

而不是

  1. for(T1 v1 : iterable1) {
  2. for (T2 v2 : iterable2) {
  3. ...
  4. for (TN vN : iterableN) {
  5. R result = f.apply(v1, v2, ..., VN);
  6. //
  7. // We are forced to perform side effects to do s.th. meaningful with the result.
  8. //
  9. }
  10. }
  11. }

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

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

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

代码示例

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

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

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

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

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

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

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

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

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

  1. ErrorTally(EventBusInterface eventBusInterface) {
  2. this.eventBusInterface = eventBusInterface;
  3. this.errors = List();
  4. }

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

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

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

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

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

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

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

  1. @Test
  2. public void waitForPermissionWithInterruption() throws Exception {
  3. when(limit.getPermission(config.getTimeoutDuration()))
  4. .then(invocation -> {
  5. LockSupport.parkNanos(5_000_000_000L);
  6. return null;
  7. });
  8. AtomicBoolean wasInterrupted = new AtomicBoolean(true);
  9. Thread thread = new Thread(() -> {
  10. wasInterrupted.set(false);
  11. Throwable cause = Try.run(() -> RateLimiter.waitForPermission(limit))
  12. .getCause();
  13. Boolean interrupted = Match(cause).of(
  14. Case($(instanceOf(IllegalStateException.class)), true)
  15. );
  16. wasInterrupted.set(interrupted);
  17. });
  18. thread.setDaemon(true);
  19. thread.start();
  20. await()
  21. .atMost(5, TimeUnit.SECONDS)
  22. .until(wasInterrupted::get, equalTo(false));
  23. thread.interrupt();
  24. await()
  25. .atMost(5, TimeUnit.SECONDS)
  26. .until(wasInterrupted::get, equalTo(true));
  27. }

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

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

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

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

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

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

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

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

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

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

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

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

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

  1. @Test
  2. public void shouldConsumeIgnoredErrorEvent() {
  3. given(helloWorldService.returnHelloWorld())
  4. .willThrow(new WebServiceException("BAM!"));
  5. RetryConfig retryConfig = RetryConfig.custom()
  6. .retryOnException(throwable -> Match(throwable).of(
  7. Case($(instanceOf(WebServiceException.class)), false),
  8. Case($(), true)))
  9. .build();
  10. retry = Retry.of("testName", retryConfig);
  11. retry.getEventPublisher()
  12. .onIgnoredError(event ->
  13. logger.info(event.getEventType().toString()));
  14. Try.ofSupplier(Retry.decorateSupplier(retry, helloWorldService::returnHelloWorld));
  15. then(logger).should(times(1)).info("IGNORED_ERROR");
  16. then(helloWorldService).should(times(1)).returnHelloWorld();
  17. }

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

  1. /**
  2. * Uploads the given media files to Twitter
  3. *
  4. * @param twitter The twitter instance to use for uploading
  5. * @param attachments The media files to upload
  6. *
  7. * @return The uploaded media files Twitter-side ids
  8. */
  9. private static List<Long> uploadMedias(final Twitter twitter, final List<File> attachments) {
  10. LOG.debug("Uploading media attachments {}", attachments);
  11. return attachments.stream()
  12. .map(unchecked((CheckedFunction1<File, UploadedMedia>) twitter::uploadMedia))
  13. .map(UploadedMedia::getMediaId)
  14. .collect(Collectors.toList());
  15. }

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

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

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

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

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

  1. @Test
  2. public void shouldConsumeIgnoredErrorEvent() {
  3. given(helloWorldService.returnHelloWorld())
  4. .willThrow(new WebServiceException("BAM!"));
  5. RetryConfig retryConfig = RetryConfig.custom()
  6. .retryOnException(throwable -> Match(throwable).of(
  7. Case($(instanceOf(WebServiceException.class)), false),
  8. Case($(), true)))
  9. .build();
  10. retry = AsyncRetry.of("testName", retryConfig);
  11. retry.getEventPublisher()
  12. .onIgnoredError(event ->
  13. logger.info(event.getEventType().toString()));
  14. Try.of(() -> awaitResult(retry.executeCompletionStage(scheduler,
  15. () -> helloWorldService.returnHelloWorld())));
  16. then(logger).should(times(1)).info("IGNORED_ERROR");
  17. then(helloWorldService).should(times(1)).returnHelloWorld();
  18. }

相关文章