io.vavr.CheckedFunction1 Java Examples

The following examples show how to use io.vavr.CheckedFunction1. 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: RateLimiterTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void decorateCheckedFunction() throws Throwable {
    CheckedFunction1<Integer, String> function = mock(CheckedFunction1.class);
    CheckedFunction1<Integer, String> decorated = RateLimiter
        .decorateCheckedFunction(limit, function);
    given(limit.acquirePermission(1)).willReturn(false);
    Try<String> decoratedFunctionResult = Try.success(1).mapTry(decorated);
    assertThat(decoratedFunctionResult.isFailure()).isTrue();
    assertThat(decoratedFunctionResult.getCause()).isInstanceOf(RequestNotPermitted.class);
    then(function).should(never()).apply(any());
    given(limit.acquirePermission(1)).willReturn(true);

    Try secondFunctionResult = Try.success(1).mapTry(decorated);

    assertThat(secondFunctionResult.isSuccess()).isTrue();
    then(function).should().apply(1);
}
 
Example #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
Source File: DecoratorInvocationHandler.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
/**
 * Applies the specified {@link FeignDecorator} to all specified {@link MethodHandler}s and
 * returns the result as a map of {@link CheckedFunction1}s. Invoking a {@link CheckedFunction1}
 * will therefore invoke the decorator which, in turn, may invoke the corresponding {@link
 * MethodHandler}.
 *
 * @param dispatch            a map of the methods from the feign interface to the {@link
 *                            MethodHandler}s.
 * @param invocationDecorator the {@link FeignDecorator} with which to decorate the {@link
 *                            MethodHandler}s.
 * @param target              the target feign interface.
 * @return a new map where the {@link MethodHandler}s are decorated with the {@link
 * FeignDecorator}.
 */
private Map<Method, CheckedFunction1<Object[], Object>> decorateMethodHandlers(
    Map<Method, MethodHandler> dispatch,
    FeignDecorator invocationDecorator, Target<?> target) {
    final Map<Method, CheckedFunction1<Object[], Object>> map = new HashMap<>();
    for (final Map.Entry<Method, MethodHandler> entry : dispatch.entrySet()) {
        final Method method = entry.getKey();
        final MethodHandler methodHandler = entry.getValue();
        if (methodHandler != null) {
            CheckedFunction1<Object[], Object> decorated = invocationDecorator
                .decorate(methodHandler::invoke, method, methodHandler, target);
            map.put(method, decorated);
        }
    }
    return map;
}
 
Example #11
Source File: BulkheadTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldChainDecoratedFunctions() {
    // tag::shouldChainDecoratedFunctions[]
    Bulkhead bulkhead = Bulkhead.of("test", config);
    Bulkhead anotherBulkhead = Bulkhead.of("testAnother", config);
    // When I create a Supplier and a Function which are decorated by different Bulkheads
    CheckedFunction0<String> decoratedSupplier
        = Bulkhead.decorateCheckedSupplier(bulkhead, () -> "Hello");
    CheckedFunction1<String, String> decoratedFunction
        = Bulkhead.decorateCheckedFunction(anotherBulkhead, (input) -> input + " world");

    // and I chain a function with map
    Try<String> result = Try.of(decoratedSupplier)
        .mapTry(decoratedFunction);

    assertThat(result.isSuccess()).isTrue();
    assertThat(result.get()).isEqualTo("Hello world");
    assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
    assertThat(anotherBulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
    // end::shouldChainDecoratedFunctions[]
}
 
Example #12
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecorateCheckedFunction() throws IOException {
    given(helloWorldService.returnHelloWorldWithNameWithException("Name"))
        .willReturn("Hello world Name");
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("helloBackend");
    CheckedFunction1<String, String> decoratedFunction = Decorators
        .ofCheckedFunction(helloWorldService::returnHelloWorldWithNameWithException)
        .withCircuitBreaker(circuitBreaker)
        .withRetry(Retry.ofDefaults("id"))
        .withRateLimiter(RateLimiter.ofDefaults("testName"))
        .withBulkhead(Bulkhead.ofDefaults("testName"))
        .decorate();

    String result = Try.of(() -> decoratedFunction.apply("Name")).get();

    assertThat(result).isEqualTo("Hello world Name");
    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
    assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(1);
}
 
Example #13
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 #14
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 #15
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 #16
Source File: CircuitBreakerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@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 #17
Source File: CircuitBreakerTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldChainDecoratedFunctions() {
    // tag::shouldChainDecoratedFunctions[]
    CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName");
    CircuitBreaker anotherCircuitBreaker = CircuitBreaker.ofDefaults("anotherTestName");
    // When I create a Supplier and a Function which are decorated by different CircuitBreakers
    CheckedFunction0<String> decoratedSupplier = CircuitBreaker
        .decorateCheckedSupplier(circuitBreaker, () -> "Hello");
    CheckedFunction1<String, String> decoratedFunction = CircuitBreaker
        .decorateCheckedFunction(anotherCircuitBreaker, (input) -> input + " world");

    // and I chain a function with map
    Try<String> result = Try.of(decoratedSupplier)
        .mapTry(decoratedFunction);

    assertThat(result.isSuccess()).isTrue();
    assertThat(result.get()).isEqualTo("Hello world");
    // end::shouldChainDecoratedFunctions[]
    CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
    assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
    assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(0);
    CircuitBreaker.Metrics metrics2 = anotherCircuitBreaker.getMetrics();
    assertThat(metrics2.getNumberOfBufferedCalls()).isEqualTo(1);
    assertThat(metrics2.getNumberOfFailedCalls()).isEqualTo(0);
}
 
Example #18
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 #19
Source File: DecoratorsTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@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 #20
Source File: VavrExceptionHandlingUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void exceptionCausingMethod_UsingTry_ThenSuccess() {
    integers.stream()
      .map(CheckedFunction1.liftTry(VavrExceptionHandlingUnitTest::readFromFile))
      .flatMap(Value::toJavaStream)
      .forEach(i -> LOG.debug("{}", i));
}
 
Example #21
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 #22
Source File: CacheEventPublisherTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConsumeOnErrorEvent() throws Throwable {
    given(cache.get("testKey")).willThrow(new RuntimeException("BLA"));
    Cache<String, String> cacheContext = Cache.of(cache);
    cacheContext.getEventPublisher().onError(
        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("ERROR");
}
 
Example #23
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 #24
Source File: TimerTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDecorateCheckedFunctionAndReturnWithSuccess() throws Throwable {
    given(helloWorldService.returnHelloWorldWithNameWithException("Tom"))
        .willReturn("Hello world Tom");
    CheckedFunction1<String, String> function = Timer.decorateCheckedFunction(timer,
        helloWorldService::returnHelloWorldWithNameWithException);

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

    assertThat(result).isEqualTo("Hello world Tom");
    assertThat(timer.getMetrics().getNumberOfTotalCalls()).isEqualTo(1);
    assertThat(timer.getMetrics().getNumberOfSuccessfulCalls()).isEqualTo(1);
    assertThat(timer.getMetrics().getNumberOfFailedCalls()).isEqualTo(0);
    then(helloWorldService).should().returnHelloWorldWithNameWithException("Tom");
}
 
Example #25
Source File: VavrExceptionHandlingUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void exceptionCausingMethod_UsingLift_ThenSuccess() {
    validIntegersOnly.stream().map(CheckedFunction1.lift(i -> readFromFile(i)))
      .map(i -> i.getOrElse(-1))
      .forEach(i -> {
          Assert.assertNotSame(-1, i);
          LOG.debug("{}", i);
      });
}
 
Example #26
Source File: VavrExceptionHandlingUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void exceptionCausingMethod_UsingLift_ThenFailure() {
    integers.stream()
      .map(CheckedFunction1.lift(i -> readFromFile(i)))
      .map(i -> i.getOrElse(-1))
      .forEach(i -> LOG.debug("{}", i));

}
 
Example #27
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 #28
Source File: TestFeignDecorator.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
public CheckedFunction1<Object[], Object> decorate(
    CheckedFunction1<Object[], Object> invocationCall,
    Method method, MethodHandler methodHandler,
    Target<?> target) {
    called = true;
    return alternativeFunction != null ? alternativeFunction : invocationCall;
}
 
Example #29
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 #30
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;
    };
}