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

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

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

API.Case介绍

暂无

代码示例

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

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

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

  1. .ringBufferSizeInClosedState(3)
  2. .recordFailure(throwable -> API.Match(throwable).of(
  3. Case($(instanceOf(WebServiceException.class)), true),
  4. Case($(), false)))
  5. .build();
  6. CircuitBreaker circuitBreaker = CircuitBreaker.of("testName", circuitBreakerConfig);

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

代码示例来源: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: com.simplyti.cloud/simple-server-core

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

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

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

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

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

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

  1. /**
  2. * Returns a new DataTable with the additional row appended.
  3. *
  4. * @param rowValues The values to append to the row.
  5. * @return Returns a new DataTable with the row appended.
  6. */
  7. public Try<DataTable> add(Object[] rowValues) {
  8. return Match(mapValuesToColumns(Stream.of(rowValues))).of(
  9. Case($Success($()), this::addRow),
  10. Case($Failure($()), Try::failure)
  11. );
  12. }

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

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

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

  1. private static CompressionOptions compressionOptions(final Configuration configuration) {
  2. if (!configuration.get(CF_COMPRESSION)) {
  3. // No compression
  4. return noCompression();
  5. }
  6. return Match(configuration.get(CF_COMPRESSION_TYPE)).of(
  7. Case($("LZ4Compressor"), lz4()),
  8. Case($("SnappyCompressor"), snappy()),
  9. Case($("DeflateCompressor"), deflate()))
  10. .withChunkLengthInKb(configuration.get(CF_COMPRESSION_BLOCK_SIZE));
  11. }

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

  1. /**
  2. * Returns a new DataTable with the additional row inserted at the specified index.
  3. *
  4. * @param idx The row index.
  5. * @param rowValues The values to insert into the row.
  6. * @return Returns a new DataTable with the row inserted.
  7. */
  8. public Try<DataTable> insert(int idx, Object[] rowValues) {
  9. return Match(mapValuesToColumns(Stream.of(rowValues))).of(
  10. Case($Success($()), values -> insertRow(idx, values)),
  11. Case($Failure($()), Try::failure)
  12. );
  13. }

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

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

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

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

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

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

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

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

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

  1. private static CompactionOptions<?> compactionOptions(final Configuration configuration) {
  2. if (!configuration.has(COMPACTION_STRATEGY)) {
  3. return null;
  4. }
  5. final CompactionOptions<?> compactionOptions = Match(configuration.get(COMPACTION_STRATEGY))
  6. .of(
  7. Case($("SizeTieredCompactionStrategy"), sizedTieredStategy()),
  8. Case($("DateTieredCompactionStrategy"), dateTieredStrategy()),
  9. Case($("LeveledCompactionStrategy"), leveledStrategy()));
  10. Array.of(configuration.get(COMPACTION_OPTIONS))
  11. .grouped(2)
  12. .forEach(keyValue -> compactionOptions.freeformOption(keyValue.get(0), keyValue.get(1)));
  13. return compactionOptions;
  14. }

相关文章