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

The following examples show how to use io.vavr.CheckedFunction1#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: 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 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 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 3
Source File: CacheTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnValueFromDecoratedCallableBecauseOfException() throws Throwable {
    given(cache.get("testKey")).willThrow(new RuntimeException("Cache is not available"));
    Cache<String, String> cacheContext = Cache.of(cache);
    TestSubscriber<CacheEvent.Type> testSubscriber =
        toFlowable(cacheContext.getEventPublisher())
            .map(CacheEvent::getEventType)
            .test();
    CheckedFunction1<String, String> cachedFunction = Cache
        .decorateCheckedSupplier(cacheContext, () -> "Hello world");

    String value = cachedFunction.apply("testKey");

    assertThat(value).isEqualTo("Hello world");
    assertThat(cacheContext.getMetrics().getNumberOfCacheHits()).isEqualTo(0);
    assertThat(cacheContext.getMetrics().getNumberOfCacheMisses()).isEqualTo(0);
    testSubscriber
        .assertValueCount(1)
        .assertValues(CacheEvent.Type.ERROR);
}
 
Example 4
Source File: DefaultFallbackHandler.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Override
public CheckedFunction1<Object[], Object> decorate(
    CheckedFunction1<Object[], Object> invocationCall,
    Method method,
    Predicate<Exception> filter) {
    validateFallback(fallback, method);
    Method fallbackMethod = getFallbackMethod(fallback, method);
    fallbackMethod.setAccessible(true);
    return args -> {
        try {
            return invocationCall.apply(args);
        } catch (Exception exception) {
            if (filter.test(exception)) {
                return fallbackMethod.invoke(fallback, args);
            }
            throw exception;
        }
    };
}
 
Example 5
Source File: FallbackFactory.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Override
public CheckedFunction1<Object[], Object> decorate(
    CheckedFunction1<Object[], Object> invocationCall,
    Method method,
    Predicate<Exception> filter) {
    return args -> {
        try {
            return invocationCall.apply(args);
        } catch (Exception exception) {
            if (filter.test(exception)) {
                T fallbackInstance = fallbackSupplier.apply(exception);
                validateFallback(fallbackInstance, method);
                Method fallbackMethod = getFallbackMethod(fallbackInstance, method);
                try {
                    return fallbackMethod.invoke(fallbackInstance, args);
                } catch (InvocationTargetException e) {
                    // Rethrow the exception thrown in the fallback wrapped by InvocationTargetException
                    throw e.getCause();
                }
            }
            throw exception;
        }
    };
}
 
Example 6
Source File: Retry.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a retryable function.
 *
 * @param retry    the retry context
 * @param function the original function
 * @param <T>      the type of the input to the function
 * @param <R>      the result type of the function
 * @return a retryable function
 */
static <T, R> CheckedFunction1<T, R> decorateCheckedFunction(Retry retry,
                                                             CheckedFunction1<T, R> function) {
    return (T t) -> {
        Retry.Context<R> context = retry.context();
        do {
            try {
                R result = function.apply(t);
                final boolean validationOfResult = context.onResult(result);
                if (!validationOfResult) {
                    context.onComplete();
                    return result;
                }
            } catch (Exception exception) {
                context.onError(exception);
            }
        } while (true);
    };
}
 
Example 7
Source File: CacheTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnCachedValue() throws Throwable {
    given(cache.get("testKey")).willReturn("Hello from cache");
    Cache<String, String> cacheContext = Cache.of(cache);
    TestSubscriber<CacheEvent.Type> testSubscriber =
        toFlowable(cacheContext.getEventPublisher())
            .map(CacheEvent::getEventType)
            .test();
    CheckedFunction1<String, String> cachedFunction = Cache
        .decorateCheckedSupplier(cacheContext, () -> "Hello world");

    String value = cachedFunction.apply("testKey");

    assertThat(value).isEqualTo("Hello from cache");
    assertThat(cacheContext.getMetrics().getNumberOfCacheHits()).isEqualTo(1);
    assertThat(cacheContext.getMetrics().getNumberOfCacheMisses()).isEqualTo(0);
    testSubscriber
        .assertValueCount(1)
        .assertValues(CacheEvent.Type.CACHE_HIT);
}
 
Example 8
Source File: CacheTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnValueOfSupplier() throws Throwable {
    given(cache.get("testKey")).willReturn(null);
    willThrow(new RuntimeException("Cache is not available")).given(cache)
        .put("testKey", "Hello world");
    Cache<String, String> cacheContext = Cache.of(cache);
    TestSubscriber<CacheEvent.Type> testSubscriber =
        toFlowable(cacheContext.getEventPublisher())
            .map(CacheEvent::getEventType)
            .test();
    CheckedFunction1<String, String> cachedFunction = Cache
        .decorateCheckedSupplier(cacheContext, () -> "Hello world");

    String value = cachedFunction.apply("testKey");

    assertThat(value).isEqualTo("Hello world");
    assertThat(cacheContext.getMetrics().getNumberOfCacheHits()).isEqualTo(0);
    assertThat(cacheContext.getMetrics().getNumberOfCacheMisses()).isEqualTo(1);
    testSubscriber
        .assertValueCount(2)
        .assertValues(CacheEvent.Type.CACHE_MISS, CacheEvent.Type.ERROR);
}
 
Example 9
Source File: CacheTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnValueFromDecoratedCallable() throws Throwable {
    given(cache.get("testKey")).willReturn(null);
    Cache<String, String> cacheContext = Cache.of(cache);
    TestSubscriber<CacheEvent.Type> testSubscriber =
        toFlowable(cacheContext.getEventPublisher())
            .map(CacheEvent::getEventType)
            .test();
    CheckedFunction1<String, String> cachedFunction = Cache
        .decorateCallable(cacheContext, () -> "Hello world");

    String value = cachedFunction.apply("testKey");

    assertThat(value).isEqualTo("Hello world");
    assertThat(cacheContext.getMetrics().getNumberOfCacheHits()).isEqualTo(0);
    assertThat(cacheContext.getMetrics().getNumberOfCacheMisses()).isEqualTo(1);
    then(cache).should().put("testKey", "Hello world");
    testSubscriber
        .assertValueCount(1)
        .assertValues(CacheEvent.Type.CACHE_MISS);
}
 
Example 10
Source File: CircuitBreakerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDecorateCheckedFunctionAndReturnWithSuccess() 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"))
        .willReturn("Hello world Tom");
    CheckedFunction1<String, String> function = CircuitBreaker
        .decorateCheckedFunction(circuitBreaker,
            helloWorldService::returnHelloWorldWithNameWithException);

    String result = function.apply("Tom");

    assertThat(result).isEqualTo("Hello world Tom");
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
    assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(0);
    assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(1);
    then(helloWorldService).should().returnHelloWorldWithNameWithException("Tom");
}
 
Example 11
Source File: CacheTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnValueFromDecoratedCheckedSupplier() throws Throwable {
    given(cache.get("testKey")).willReturn(null);
    Cache<String, String> cacheContext = Cache.of(cache);
    TestSubscriber<CacheEvent.Type> testSubscriber =
        toFlowable(cacheContext.getEventPublisher())
            .map(CacheEvent::getEventType)
            .test();
    CheckedFunction1<String, String> cachedFunction = Cache
        .decorateCheckedSupplier(cacheContext, () -> "Hello world");

    String value = cachedFunction.apply("testKey");

    assertThat(value).isEqualTo("Hello world");
    assertThat(cacheContext.getMetrics().getNumberOfCacheHits()).isEqualTo(0);
    assertThat(cacheContext.getMetrics().getNumberOfCacheMisses()).isEqualTo(1);
    then(cache).should().put("testKey", "Hello world");
    testSubscriber
        .assertValueCount(1)
        .assertValues(CacheEvent.Type.CACHE_MISS);
}
 
Example 12
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 13
Source File: CacheEventPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConsumeOnCacheMissEvent() throws Throwable {
    given(cache.get("testKey")).willReturn(null);
    Cache<String, String> cacheContext = Cache.of(cache);
    cacheContext.getEventPublisher().onCacheMiss(
        event -> logger.info(event.getEventType().toString()));
    CheckedFunction1<String, String> cachedFunction = Cache
        .decorateCheckedSupplier(cacheContext, () -> "Hello world");

    String value = cachedFunction.apply("testKey");

    assertThat(value).isEqualTo("Hello world");
    then(logger).should(times(1)).info("CACHE_MISS");
}
 
Example 14
Source File: CacheEventPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConsumeOnCacheHitEvent() throws Throwable {
    given(cache.get("testKey")).willReturn("Hello world");
    Cache<String, String> cacheContext = Cache.of(cache);
    cacheContext.getEventPublisher().onCacheHit(
        event -> logger.info(event.getEventType().toString()));
    CheckedFunction1<String, String> cachedFunction = Cache
        .decorateCheckedSupplier(cacheContext, () -> "Hello world");

    String value = cachedFunction.apply("testKey");

    assertThat(value).isEqualTo("Hello world");
    then(logger).should(times(1)).info("CACHE_HIT");
}
 
Example 15
Source File: CallMeter.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a timed function.
 *
 * @param meter    the call meter to use
 * @param function the original function
 * @return a timed function
 */
static <T, R> CheckedFunction1<T, R> decorateCheckedFunction(CallMeterBase meter,
    CheckedFunction1<T, R> function) {
    return (T t) -> {
        final Timer timer = meter.startTimer();
        try {
            R returnValue = function.apply(t);
            timer.onSuccess();
            return returnValue;
        } catch (Throwable e) {
            timer.onError();
            throw e;
        }
    };
}
 
Example 16
Source File: Timer.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a timed function.
 *
 * @param timer    the timer to use
 * @param function the original function
 * @return a timed function
 */
static <T, R> CheckedFunction1<T, R> decorateCheckedFunction(Timer timer,
    CheckedFunction1<T, R> function) {
    return (T t) -> {
        final Timer.Context context = timer.context();
        try {
            R returnValue = function.apply(t);
            context.onSuccess();
            return returnValue;
        } catch (Throwable e) {
            context.onError();
            throw e;
        }
    };
}
 
Example 17
Source File: Bulkhead.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a function which is decorated by a bulkhead.
 *
 * @param bulkhead the bulkhead
 * @param function the original function
 * @param <T>      the type of the input to the function
 * @param <R>      the type of the result of the function
 * @return a function which is decorated by a bulkhead.
 */
static <T, R> CheckedFunction1<T, R> decorateCheckedFunction(Bulkhead bulkhead,
    CheckedFunction1<T, R> function) {
    return (T t) -> {
        bulkhead.acquirePermission();
        try {
            return function.apply(t);
        } finally {
            bulkhead.onComplete();
        }
    };
}
 
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 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 19
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 <A1, T> io.vavr.Function1<A1, T> unchecked(CheckedFunction1<A1, T> f) {
    return a1 -> { try {
        return f.apply(a1);
    } catch (Throwable x) {
        throwSilently(x);
        return null; // code never reaches here
    }};
}
 
Example 20
Source File: RateLimiter.java    From resilience4j with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a function which is restricted by a RateLimiter.
 *
 * @param rateLimiter       the RateLimiter
 * @param permitsCalculator calculates the number of permits required by this call based on the
 *                          functions argument
 * @param function          the original function
 * @param <T>               the type of function argument
 * @param <R>               the type of function results
 * @return a function which is restricted by a RateLimiter.
 */
static <T, R> CheckedFunction1<T, R> decorateCheckedFunction(RateLimiter rateLimiter,
    Function<T, Integer> permitsCalculator, CheckedFunction1<T, R> function) {
    return (T t) -> {
        waitForPermission(rateLimiter, permitsCalculator.apply(t));
        return function.apply(t);
    };
}