Java Code Examples for io.vavr.CheckedFunction0#apply()

The following examples show how to use io.vavr.CheckedFunction0#apply() . 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: TimerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDecorateCheckedSupplier() throws Throwable {
    given(helloWorldService.returnHelloWorldWithException()).willReturn("Hello world");
    CheckedFunction0<String> timedSupplier = Timer
        .decorateCheckedSupplier(timer, helloWorldService::returnHelloWorldWithException);

    String value = timedSupplier.apply();

    assertThat(timer.getMetrics().getNumberOfTotalCalls()).isEqualTo(1);
    assertThat(timer.getMetrics().getNumberOfSuccessfulCalls()).isEqualTo(1);
    assertThat(timer.getMetrics().getNumberOfFailedCalls()).isEqualTo(0);
    assertThat(metricRegistry.getCounters().size()).isEqualTo(2);
    assertThat(metricRegistry.getTimers().size()).isEqualTo(1);
    assertThat(value).isEqualTo("Hello world");
    then(helloWorldService).should(times(1)).returnHelloWorldWithException();
}
 
Example 2
Source File: CheckFunctionUtils.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a composed function that first executes the function and optionally recovers from an
 * exception.
 *
 * @param <T>              return type of after
 * @param function the function which should be recovered from a certain exception
 * @param exceptionTypes the specific exception types that should be recovered
 * @param exceptionHandler the exception handler
 * @return a function composed of supplier and exceptionHandler
 */
public static <T> CheckedFunction0<T> recover(CheckedFunction0<T> function,
    List<Class<? extends Throwable>> exceptionTypes,
    CheckedFunction1<Throwable, T> exceptionHandler) {
    return () -> {
        try {
            return function.apply();
        } catch (Exception exception) {
            if(exceptionTypes.stream().anyMatch(exceptionType -> exceptionType.isAssignableFrom(exception.getClass()))){
                return exceptionHandler.apply(exception);
            }else{
                throw exception;
            }
        }
    };
}
 
Example 3
Source File: CheckFunctionUtils.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a composed function that first executes the function and optionally recovers from an
 * exception.
 *
 * @param <T>              return type of after
 * @param function the function which should be recovered from a certain exception
 * @param exceptionType the specific exception type that should be recovered
 * @param exceptionHandler the exception handler
 * @return a function composed of callable and exceptionHandler
 */
public static <X extends Throwable, T> CheckedFunction0<T> recover(CheckedFunction0<T> function,
    Class<X> exceptionType,
    CheckedFunction1<Throwable, T> exceptionHandler) {
    return () -> {
        try {
            return function.apply();
        } catch (Throwable throwable) {
            if(exceptionType.isAssignableFrom(throwable.getClass())) {
                return exceptionHandler.apply(throwable);
            }else{
                throw throwable;
            }
        }
    };
}
 
Example 4
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecorateCheckedSupplierWithFallback() throws Throwable {
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
    circuitBreaker.transitionToOpenState();

    CheckedFunction0<String> checkedSupplier = Decorators
        .ofCheckedSupplier(() -> helloWorldService.returnHelloWorldWithException())
        .withCircuitBreaker(circuitBreaker)
        .withFallback(CallNotPermittedException.class, e -> "Fallback")
        .decorate();

    String result = checkedSupplier.apply();

    assertThat(result).isEqualTo("Fallback");
    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfNotPermittedCalls()).isEqualTo(1);
    then(helloWorldService).should(never()).returnHelloWorld();
}
 
Example 5
Source File: CircuitBreakerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDecorateCheckedSupplierAndReturnWithSuccess() throws Throwable {
    CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults();
    CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("testName");
    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(0);
    given(helloWorldService.returnHelloWorldWithException()).willReturn("Hello world");
    CheckedFunction0<String> checkedSupplier = circuitBreaker
        .decorateCheckedSupplier(helloWorldService::returnHelloWorldWithException);

    String result = checkedSupplier.apply();

    assertThat(result).isEqualTo("Hello world");
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
    assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(0);
    assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(1);
    then(helloWorldService).should().returnHelloWorldWithException();
}
 
Example 6
Source File: Retry.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a retryable supplier.
 *
 * @param retry    the retry context
 * @param supplier the original function
 * @param <T>      the type of results supplied by this supplier
 * @return a retryable function
 */
static <T> CheckedFunction0<T> decorateCheckedSupplier(Retry retry,
                                                       CheckedFunction0<T> supplier) {
    return () -> {
        Retry.Context<T> context = retry.context();
        do {
            try {
                T result = supplier.apply();
                final boolean validationOfResult = context.onResult(result);
                if (!validationOfResult) {
                    context.onComplete();
                    return result;
                }
            } catch (Exception exception) {
                context.onError(exception);
            }
        } while (true);
    };
}
 
Example 7
Source File: Bulkhead.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a supplier which is decorated by a bulkhead.
 *
 * @param bulkhead the Bulkhead
 * @param supplier the original supplier
 * @param <T>      the type of results supplied by this supplier
 * @return a supplier which is decorated by a Bulkhead.
 */
static <T> CheckedFunction0<T> decorateCheckedSupplier(Bulkhead bulkhead,
    CheckedFunction0<T> supplier) {
    return () -> {
        bulkhead.acquirePermission();
        try {
            return supplier.apply();
        } finally {
            bulkhead.onComplete();
        }
    };
}
 
Example 8
Source File: Timer.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a timed checked supplier.
 *
 * @param timer    the timer to use
 * @param supplier the original supplier
 * @return a timed supplier
 */
static <T> CheckedFunction0<T> decorateCheckedSupplier(Timer timer,
    CheckedFunction0<T> supplier) {
    return () -> {
        final Timer.Context context = timer.context();
        try {
            T returnValue = supplier.apply();
            context.onSuccess();
            return returnValue;
        } catch (Throwable e) {
            context.onError();
            throw e;
        }
    };
}
 
Example 9
Source File: DefaultFallbackDecorator.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
public CheckedFunction0<Object> decorate(FallbackMethod fallbackMethod,
    CheckedFunction0<Object> supplier) {
    return () -> {
        try {
            return supplier.apply();
        } catch (IllegalReturnTypeException e) {
            throw e;
        } catch (Throwable throwable) {
            return fallbackMethod.fallback(throwable);
        }
    };
}
 
Example 10
Source File: CallMeter.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a timed checked supplier.
 *
 * @param meter    the call meter to use
 * @param supplier the original supplier
 * @return a timed supplier
 */
static <T> CheckedFunction0<T> decorateCheckedSupplier(CallMeterBase meter,
    CheckedFunction0<T> supplier) {
    return () -> {
        final Timer timer = meter.startTimer();
        try {
            final T returnValue = supplier.apply();
            timer.onSuccess();
            return returnValue;
        } catch (Throwable e) {
            timer.onError();
            throw e;
        }
    };
}
 
Example 11
Source File: BulkheadTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDecorateCheckedSupplierAndReturnWithSuccess() throws Throwable {
    Bulkhead bulkhead = Bulkhead.of("test", config);
    given(helloWorldService.returnHelloWorldWithException()).willReturn("Hello world");
    CheckedFunction0<String> checkedSupplier = Bulkhead
        .decorateCheckedSupplier(bulkhead, helloWorldService::returnHelloWorldWithException);

    String result = checkedSupplier.apply();

    assertThat(result).isEqualTo("Hello world");
    assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
    then(helloWorldService).should(times(1)).returnHelloWorldWithException();
}
 
Example 12
Source File: Lambdas.java    From ts-reaktive with MIT License 5 votes vote down vote up
/**
 * Removes any thrown exceptions from the signature of the given lambda, while still throwing them.
 * Only safe when you can guarantee that the calling method actually declares the given checked exception.
 */
public static <T> io.vavr.Function0<T> unchecked(CheckedFunction0<T> f) {
    return () -> { try {
        return f.apply();
    } catch (Throwable x) {
        throwSilently(x);
        return null; // code never reaches here
    }};
}
 
Example 13
Source File: CheckFunctionUtilsTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test(expected = RuntimeException.class)
public void shouldRethrowException2() throws Throwable {
    CheckedFunction0<String> callable = () -> {
        throw new RuntimeException("BAM!");
    };
    CheckedFunction0<String> callableWithRecovery = CheckFunctionUtils.recover(callable, IllegalArgumentException.class, (ex) -> "Bla");

    callableWithRecovery.apply();
}
 
Example 14
Source File: CheckFunctionUtilsTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test(expected = RuntimeException.class)
public void shouldRethrowException() throws Throwable {
    CheckedFunction0<String> callable = () -> {
        throw new IOException("BAM!");
    };
    CheckedFunction0<String> callableWithRecovery = CheckFunctionUtils.recover(callable, (ex) -> {
        throw new RuntimeException();
    });

    callableWithRecovery.apply();
}
 
Example 15
Source File: CheckFunctionUtilsTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRecoverFromSpecificExceptions() throws Throwable {
    CheckedFunction0<String> callable = () -> {
        throw new IOException("BAM!");
    };

    CheckedFunction0<String> callableWithRecovery = CheckFunctionUtils.recover(callable,
        asList(IllegalArgumentException.class, IOException.class),
        (ex) -> "Bla");

    String result = callableWithRecovery.apply();

    assertThat(result).isEqualTo("Bla");
}
 
Example 16
Source File: CheckFunctionUtilsTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRecoverFromException() throws Throwable {
    CheckedFunction0<String> callable = () -> {
        throw new IOException("BAM!");
    };
    CheckedFunction0<String> callableWithRecovery = CheckFunctionUtils.recover(callable, (ex) -> "Bla");

    String result = callableWithRecovery.apply();

    assertThat(result).isEqualTo("Bla");
}
 
Example 17
Source File: CheckFunctionUtils.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a composed function that first executes the function and optionally recovers from a specific result.
 *
 * @param <T>              return type of after
 * @param function the function
 * @param resultPredicate the result predicate
 * @param resultHandler the result handler
 * @return a function composed of supplier and exceptionHandler
 */
public static <T> CheckedFunction0<T> recover(CheckedFunction0<T> function,
    Predicate<T> resultPredicate, CheckedFunction1<T, T> resultHandler) {
    return () -> {
        T result = function.apply();
        if(resultPredicate.test(result)){
            return resultHandler.apply(result);
        }
        return result;
    };
}
 
Example 18
Source File: CheckFunctionUtils.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a composed function that first executes the function and optionally recovers from an
 * exception.
 *
 * @param <T>              return type of after
 * @param function the function which should be recovered from a certain exception
 * @param exceptionHandler the exception handler
 * @return a function composed of callable and exceptionHandler
 */
public static <T> CheckedFunction0<T> recover(CheckedFunction0<T> function,
    CheckedFunction1<Throwable, T> exceptionHandler) {
    return () -> {
        try {
            return function.apply();
        } catch (Throwable throwable) {
            return exceptionHandler.apply(throwable);
        }
    };
}
 
Example 19
Source File: RateLimiter.java    From resilience4j with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a supplier which is restricted by a RateLimiter.
 *
 * @param rateLimiter the RateLimiter
 * @param permits     number of permits that this call requires
 * @param supplier    the original supplier
 * @param <T>         the type of results supplied supplier
 * @return a supplier which is restricted by a RateLimiter.
 */
static <T> CheckedFunction0<T> decorateCheckedSupplier(RateLimiter rateLimiter, int permits,
    CheckedFunction0<T> supplier) {
    return () -> {
        waitForPermission(rateLimiter, permits);
        return supplier.apply();
    };
}