io.vavr.API.Match()方法的使用及代码示例

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

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

API.Match介绍

[英]Entry point of the match API.
[中]match API的入口点。

代码示例

代码示例来源: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: resilience4j/resilience4j

.ringBufferSizeInHalfOpenState(2)
.waitDurationInOpenState(Duration.ofMillis(1000))
.recordFailure(throwable -> Match(throwable).of(
    Case($(instanceOf(WebServiceException.class)), true),
    Case($(), false)))

代码示例来源: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: 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: 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: resilience4j/resilience4j

.recordFailure(throwable -> API.Match(throwable).of(
    Case($(instanceOf(WebServiceException.class)), true),
    Case($(), false)))

代码示例来源: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: 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: 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();
}

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

/**
 * Dynamically either sends a normal tweet or a reply depending on whether the controller was used to prepare a
 * "normal" new tweet or a reply (i.e. if there was a value set for {@link #inReplyStatus}.
 */
private void send() {
  Match(inReplyStatus.getValue()).of(
      Case($(Objects::nonNull), this::sendReply),
      Case($(Objects::isNull), this::sendTweet)
  ).thenRunAsync(
      () -> Stream.of(timeline, mentions).forEach(RateLimited::refresh),
      CompletableFuture.delayedExecutor(2, TimeUnit.SECONDS)
  );
}

代码示例来源:origin: pivovarit/articles

private String toHammingCodeValue(int it, BinaryString input) {
    return Match(it + 1).of(
     Case($(HammingHelper::isPowerOfTwo), () -> helper.getParityBit(it, input)),
     Case($(), () -> helper.getDataBit(it, input))
    );
  }
}

代码示例来源:origin: com.simplyti.cloud/simple-server-core

@Override
public Class<? extends ServerSocketChannel> get() {
  return Match(eventLoopGroup).of(
      Case($(instanceOf(EpollEventLoopGroup.class)), EpollServerSocketChannel.class),
      Case($(instanceOf(KQueueEventLoopGroup.class)), KQueueServerSocketChannel.class),
      Case($(), NioServerSocketChannel.class));
}

代码示例来源:origin: martincooper/java-datatable

private Try<DataTable> buildTable(Try<Seq<IDataColumn>> columns) {
  return Match(columns).of(
      Case($Success($()), cols -> DataTable.build(table.name(), cols)),
      Case($Failure($()), Try::failure)
  );
}

代码示例来源:origin: martincooper/java-datatable

/**
 * Returns a new DataTable with the additional row appended.
 *
 * @param rowValues The values to append to the row.
 * @return Returns a new DataTable with the row appended.
 */
public Try<DataTable> add(Object[] rowValues) {
  return Match(mapValuesToColumns(Stream.of(rowValues))).of(
      Case($Success($()), this::addRow),
      Case($Failure($()), Try::failure)
  );
}

代码示例来源:origin: martincooper/java-datatable

/**
 * Builds an instance of a DataTable.
 * Columns are validated before creation, returning a Failure on error.
 *
 * @param tableName The name of the table.
 * @param columns The column collection.
 * @return Returns a DataTable wrapped in a Try.
 */
public static Try<DataTable> build(String tableName, Stream<IDataColumn> columns) {
  return Match(validateColumns(columns)).of(
   Case($Success($()), cols -> Try.success(new DataTable(tableName, cols))),
   Case($Failure($()), Try::failure)
  );
}

代码示例来源:origin: martincooper/java-datatable

/**
 * Returns a new DataTable with the additional row inserted at the specified index.
 *
 * @param idx The row index.
 * @param rowValues The values to insert into the row.
 * @return Returns a new DataTable with the row inserted.
 */
public Try<DataTable> insert(int idx, Object[] rowValues) {
  return Match(mapValuesToColumns(Stream.of(rowValues))).of(
      Case($Success($()), values -> insertRow(idx, values)),
      Case($Failure($()), Try::failure)
  );
}

代码示例来源:origin: martincooper/java-datatable

/**
 * Returns a new DataTable with the data replaced at the specified index.
 *
 * @param idx The row index.
 * @param rowValues The new values to replaced the old ones.
 * @return Returns a new DataTable with the row inserted.
 */
public Try<DataTable> replace(int idx, Object[] rowValues) {
  return Match(mapValuesToColumns(Stream.of(rowValues))).of(
      Case($Success($()), values -> replaceRow(idx, values)),
      Case($Failure($()), Try::failure)
  );
}

代码示例来源:origin: pivovarit/articles

@Override
public BinaryString decode(EncodedString input) {
  EncodedString corrected = Match(indexesOfInvalidParityBits(input).isEmpty()).of(
   Case($(true), () -> input),
   Case($(false), () -> withBitFlippedAt(input, indexesOfInvalidParityBits(input).reduce((a, b) -> a + b) - 1))
  );
  return extractor.stripHammingMetadata(corrected);
}

代码示例来源:origin: martincooper/java-datatable

/**
 * Attempts to add / append a new item to the end of the column.
 * A type check is performed before addition.
 *
 * @param value The item required to be added.
 * @return Returns a Success with the new modified DataColumn, or a Failure.
 */
@Override
public Try<IDataColumn> add(Object value) {
  return Match(GenericExtensions.tryCast(this.type, value)).of(
      Case($Success($()), typedVal -> Try.of(() -> createColumn(this.data.append(typedVal)))),
      Case($Failure($()), DataTableException.tryError("tryAdd failed. Item of invalid type passed."))
  );
}

代码示例来源:origin: org.janusgraph/janusgraph-cql

private static CompressionOptions compressionOptions(final Configuration configuration) {
  if (!configuration.get(CF_COMPRESSION)) {
    // No compression
    return noCompression();
  }
  return Match(configuration.get(CF_COMPRESSION_TYPE)).of(
      Case($("LZ4Compressor"), lz4()),
      Case($("SnappyCompressor"), snappy()),
      Case($("DeflateCompressor"), deflate()))
      .withChunkLengthInKb(configuration.get(CF_COMPRESSION_BLOCK_SIZE));
}

相关文章