Java Code Examples for io.vavr.control.Try#of()
The following examples show how to use
io.vavr.control.Try#of() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SupplierRetryTest.java From resilience4j with Apache License 2.0 | 7 votes |
@Test public void shouldReturnAfterOneAttemptAndIgnoreException() { given(helloWorldService.returnHelloWorld()).willThrow(new HelloWorldException()); RetryConfig config = RetryConfig.custom() .retryOnException(throwable -> API.Match(throwable).of( API.Case($(Predicates.instanceOf(HelloWorldException.class)), false), API.Case($(), true))) .build(); Retry retry = Retry.of("id", config); CheckedFunction0<String> retryableSupplier = Retry .decorateCheckedSupplier(retry, helloWorldService::returnHelloWorld); Try<String> result = Try.of(retryableSupplier); // Because the exception should be rethrown immediately. then(helloWorldService).should().returnHelloWorld(); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(HelloWorldException.class); assertThat(sleptTime).isEqualTo(0); }
Example 2
Source File: RateLimiterTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void decorateCheckedSupplier() throws Throwable { CheckedFunction0 supplier = mock(CheckedFunction0.class); CheckedFunction0 decorated = RateLimiter.decorateCheckedSupplier(limit, supplier); given(limit.acquirePermission(1)).willReturn(false); Try decoratedSupplierResult = Try.of(decorated); assertThat(decoratedSupplierResult.isFailure()).isTrue(); assertThat(decoratedSupplierResult.getCause()).isInstanceOf(RequestNotPermitted.class); then(supplier).should(never()).apply(); given(limit.acquirePermission(1)).willReturn(true); Try secondSupplierResult = Try.of(decorated); assertThat(secondSupplierResult.isSuccess()).isTrue(); then(supplier).should().apply(); }
Example 3
Source File: CircuitBreakerTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldDecorateCheckedFunctionAndReturnWithException() throws Throwable { CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults(); CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("testName"); CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(0); given(helloWorldService.returnHelloWorldWithNameWithException("Tom")) .willThrow(new RuntimeException("BAM!")); CheckedFunction1<String, String> function = CircuitBreaker .decorateCheckedFunction(circuitBreaker, helloWorldService::returnHelloWorldWithNameWithException); Try<String> result = Try.of(() -> function.apply("Tom")); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(RuntimeException.class); assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1); assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1); assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(0); }
Example 4
Source File: CompletionStageRetryTest.java From resilience4j with Apache License 2.0 | 6 votes |
private void shouldCompleteFutureAfterAttemptsInCaseOfExceptionAtAsyncStage(int noOfAttempts) { CompletableFuture<String> failedFuture = new CompletableFuture<>(); failedFuture.completeExceptionally(new HelloWorldException()); given(helloWorldService.returnHelloWorld()) .willReturn(failedFuture); Retry retryContext = Retry.of( "id", RetryConfig .custom() .maxAttempts(noOfAttempts) .build()); Supplier<CompletionStage<String>> supplier = Retry.decorateCompletionStage( retryContext, scheduler, () -> helloWorldService.returnHelloWorld()); Try<String> resultTry = Try.of(() -> awaitResult(supplier.get())); then(helloWorldService).should(times(noOfAttempts)).returnHelloWorld(); assertThat(resultTry.isFailure()).isTrue(); assertThat(resultTry.getCause().getCause()).isInstanceOf(HelloWorldException.class); }
Example 5
Source File: DecoratorsTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void testDecoratorBuilderWithRateLimiter() { given(helloWorldService.returnHelloWorld()).willReturn("Hello world"); RateLimiterConfig config = RateLimiterConfig.custom() .timeoutDuration(Duration.ofMillis(100)) .limitRefreshPeriod(Duration.ofSeconds(1)) .limitForPeriod(1) .build(); RateLimiter rateLimiter = RateLimiter.of("backendName", config); CheckedFunction0<String> restrictedSupplier = Decorators .ofCheckedSupplier(() -> helloWorldService.returnHelloWorld()) .withRateLimiter(rateLimiter) .decorate(); alignTime(rateLimiter); Try<String> firstTry = Try.of(restrictedSupplier); Try<String> secondTry = Try.of(restrictedSupplier); assertThat(firstTry.isSuccess()).isTrue(); assertThat(secondTry.isFailure()).isTrue(); assertThat(secondTry.getCause()).isInstanceOf(RequestNotPermitted.class); then(helloWorldService).should(times(1)).returnHelloWorld(); }
Example 6
Source File: CircuitBreakerTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldDecorateFunctionAndReturnWithException() throws Throwable { CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults(); CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("testName"); CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(0); given(helloWorldService.returnHelloWorldWithName("Tom")) .willThrow(new RuntimeException("BAM!")); Function<String, String> function = CircuitBreaker .decorateFunction(circuitBreaker, helloWorldService::returnHelloWorldWithName); Try<String> result = Try.of(() -> function.apply("Tom")); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(RuntimeException.class); assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1); assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1); assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(0); }
Example 7
Source File: SupplierRetryTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldTakeIntoAccountBackoffFunction() { given(helloWorldService.returnHelloWorld()).willThrow(new HelloWorldException()); RetryConfig config = RetryConfig.custom() .intervalFunction(IntervalFunction.ofExponentialBackoff(500, 2.0)) .build(); Retry retry = Retry.of("id", config); CheckedFunction0<String> retryableSupplier = Retry .decorateCheckedSupplier(retry, helloWorldService::returnHelloWorld); Try.of(retryableSupplier); then(helloWorldService).should(times(3)).returnHelloWorld(); assertThat(sleptTime).isEqualTo( RetryConfig.DEFAULT_WAIT_DURATION + RetryConfig.DEFAULT_WAIT_DURATION * 2); }
Example 8
Source File: CircuitBreakerTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldDecorateCheckedSupplierAndReturnWithException() throws Throwable { CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults(); CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("testName"); CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(0); given(helloWorldService.returnHelloWorldWithException()) .willThrow(new RuntimeException("BAM!")); CheckedFunction0<String> checkedSupplier = circuitBreaker .decorateCheckedSupplier(helloWorldService::returnHelloWorldWithException); Try<String> result = Try.of(checkedSupplier); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(RuntimeException.class); assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1); assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1); assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(0); then(helloWorldService).should().returnHelloWorldWithException(); }
Example 9
Source File: BulkheadTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void shouldDecorateCheckedFunctionAndReturnWithException() throws Throwable { Bulkhead bulkhead = Bulkhead.of("test", config); given(helloWorldService.returnHelloWorldWithNameWithException("Tom")) .willThrow(new RuntimeException("BAM!")); CheckedFunction1<String, String> function = Bulkhead .decorateCheckedFunction(bulkhead, helloWorldService::returnHelloWorldWithNameWithException); Try<String> result = Try.of(() -> function.apply("Tom")); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(RuntimeException.class); assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1); }
Example 10
Source File: ExpiringHolds.java From library with MIT License | 5 votes |
public Try<BatchResult> expireHolds() { return Try.of(() -> find.queryForHoldsToExpireSheet() .toStreamOfEvents() .map(this::publish) .find(Try::isFailure) .map(handleEventError -> BatchResult.SomeFailed) .getOrElse(BatchResult.FullSuccess)); }
Example 11
Source File: SupplierRetryTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void shouldReturnSuccessfullyAfterSecondAttempt() { given(helloWorldService.returnHelloWorld()) .willThrow(new HelloWorldException()) .willReturn("Hello world"); Retry retry = Retry.ofDefaults("id"); CheckedFunction0<String> retryableSupplier = Retry .decorateCheckedSupplier(retry, helloWorldService::returnHelloWorld); Try<String> result = Try.of(retryableSupplier); then(helloWorldService).should(times(2)).returnHelloWorld(); assertThat(result.get()).isEqualTo("Hello world"); assertThat(sleptTime).isEqualTo(RetryConfig.DEFAULT_WAIT_DURATION); }
Example 12
Source File: BulkheadTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void shouldDecorateCheckedSupplierAndReturnWithException() throws Throwable { Bulkhead bulkhead = Bulkhead.of("test", config); given(helloWorldService.returnHelloWorldWithException()) .willThrow(new RuntimeException("BAM!")); CheckedFunction0<String> checkedSupplier = Bulkhead .decorateCheckedSupplier(bulkhead, helloWorldService::returnHelloWorldWithException); Try<String> result = Try.of(checkedSupplier); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(RuntimeException.class); assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1); then(helloWorldService).should(times(1)).returnHelloWorldWithException(); }
Example 13
Source File: BulkheadTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void shouldDecorateSupplierAndReturnWithException() { Bulkhead bulkhead = Bulkhead.of("test", config); given(helloWorldService.returnHelloWorld()).willThrow(new RuntimeException("BAM!")); Supplier<String> supplier = Bulkhead .decorateSupplier(bulkhead, helloWorldService::returnHelloWorld); Try<String> result = Try.of(supplier::get); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(RuntimeException.class); assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1); then(helloWorldService).should(times(1)).returnHelloWorld(); }
Example 14
Source File: DecoratorsTest.java From resilience4j with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Test public void testDecorateCheckedSupplierWithCache() { javax.cache.Cache<String, String> cache = mock(javax.cache.Cache.class); given(cache.containsKey("testKey")).willReturn(true); given(cache.get("testKey")).willReturn("Hello from cache"); CheckedFunction1<String, String> cachedFunction = Decorators .ofCheckedSupplier(() -> "Hello world") .withCache(Cache.of(cache)) .decorate(); Try<String> value = Try.of(() -> cachedFunction.apply("testKey")); assertThat(value).contains("Hello from cache"); }
Example 15
Source File: W3CShaclTestSuite.java From RDFUnit with Apache License 2.0 | 5 votes |
private Try<TestExecution> runShapes() { return Try.of(() -> { val shapesSource = SchemaSourceFactory.createSchemaSourceSimple( getId(), getShapesGraphUri(), new RdfModelReader(getShapesGraph()) ); Set<GenericTestCase> tests = ImmutableSet.copyOf(new ShaclTestGenerator().generate(shapesSource)); val testSuite = new TestSuite(tests); return RDFUnitStaticValidator.validate(shaclTestCaseResult, getDataGraph(), testSuite); }); }
Example 16
Source File: CancelingHold.java From library with MIT License | 5 votes |
public Try<Result> cancelHold(@NonNull CancelHoldCommand command) { return Try.of(() -> { BookOnHold bookOnHold = find(command.getBookId(), command.getPatronId()); Patron patron = find(command.getPatronId()); Either<BookHoldCancelingFailed, BookHoldCanceled> result = patron.cancelHold(bookOnHold); return Match(result).of( Case($Left($()), this::publishEvents), Case($Right($()), this::publishEvents) ); }); }
Example 17
Source File: KanelaConfiguration.java From kanela with Apache License 2.0 | 4 votes |
private Try<String> getTypeListPattern(Config config, String path) { return Try.of(() -> List.ofAll(config.getStringList(path)).mkString("|")); }
Example 18
Source File: Jar.java From kanela with Apache License 2.0 | 4 votes |
public static Try<URL> getKanelaJar() { return Try.of(() -> { val location = Kanela.class.getProtectionDomain().getCodeSource().getLocation(); return Paths.get(location.toURI()).toUri().toURL(); }); }
Example 19
Source File: VavrUnitTest.java From tutorials with MIT License | 4 votes |
@Test public void givenBadCode_whenTryHandles_thenCorrect() { Try<Integer> result = Try.of(() -> 1 / 0); assertTrue(result.isFailure()); }
Example 20
Source File: DataColumn.java From java-datatable with Apache License 2.0 | 2 votes |
/** * Removes the item at the specified index. * * @param index The index to remove the item at. * @return Returns a new DataColumn with the specified item removed. */ public Try<DataColumn<T>> removeItem(Integer index) { return Try.of(() -> createColumn(this.data.removeAt(index))); }