Java Code Examples for io.vavr.control.Try#run()
The following examples show how to use
io.vavr.control.Try#run() .
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: EventPublisherTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldIgnoreError() { willThrow(new HelloWorldException()).willDoNothing().given(helloWorldService) .sayHelloWorld(); RetryConfig config = RetryConfig.custom() .retryOnException(t -> t instanceof IOException) .maxAttempts(3).build(); Retry retry = Retry.of("id", config); TestSubscriber<RetryEvent.Type> testSubscriber = toFlowable(retry.getEventPublisher()) .map(RetryEvent::getEventType) .test(); CheckedRunnable retryableRunnable = Retry .decorateCheckedRunnable(retry, helloWorldService::sayHelloWorld); Try<Void> result = Try.run(retryableRunnable); then(helloWorldService).should().sayHelloWorld(); assertThat(result.isFailure()).isTrue(); assertThat(sleptTime).isEqualTo(0); testSubscriber.assertValueCount(1).assertValues(RetryEvent.Type.IGNORED_ERROR); }
Example 2
Source File: EventPublisherTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldReturnAfterTwoAttempts() { willThrow(new HelloWorldException()).willDoNothing().given(helloWorldService) .sayHelloWorld(); Retry retry = Retry.ofDefaults("id"); TestSubscriber<RetryEvent.Type> testSubscriber = toFlowable(retry.getEventPublisher()) .map(RetryEvent::getEventType) .test(); CheckedRunnable retryableRunnable = Retry .decorateCheckedRunnable(retry, helloWorldService::sayHelloWorld); Try<Void> result = Try.run(retryableRunnable); then(helloWorldService).should(times(2)).sayHelloWorld(); assertThat(result.isSuccess()).isTrue(); assertThat(sleptTime).isEqualTo(RetryConfig.DEFAULT_WAIT_DURATION); testSubscriber.assertValueCount(2) .assertValues(RetryEvent.Type.RETRY, RetryEvent.Type.SUCCESS); }
Example 3
Source File: RateLimiterTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void decorateCheckedRunnable() throws Throwable { CheckedRunnable runnable = mock(CheckedRunnable.class); CheckedRunnable decorated = RateLimiter.decorateCheckedRunnable(limit, runnable); given(limit.acquirePermission(1)).willReturn(false); Try decoratedRunnableResult = Try.run(decorated); assertThat(decoratedRunnableResult.isFailure()).isTrue(); assertThat(decoratedRunnableResult.getCause()).isInstanceOf(RequestNotPermitted.class); then(runnable).should(never()).run(); given(limit.acquirePermission(1)).willReturn(true); Try secondRunnableResult = Try.run(decorated); assertThat(secondRunnableResult.isSuccess()).isTrue(); then(runnable).should().run(); }
Example 4
Source File: CircuitBreakerTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldDecorateConsumerAndReturnWithException() throws Throwable { CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults(); CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("testName"); CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(0); Consumer<String> consumer = circuitBreaker.decorateConsumer((value) -> { throw new RuntimeException("BAM!"); }); Try<Void> result = Try.run(() -> consumer.accept("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 5
Source File: CircuitBreakerTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldReturnFailureWithRuntimeException() { CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("testName"); assertThat(circuitBreaker.getState()).isEqualTo(CircuitBreaker.State.CLOSED); CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(0); assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(0); CheckedRunnable checkedRunnable = circuitBreaker.decorateCheckedRunnable(() -> { throw new RuntimeException("BAM!"); }); Try result = Try.run(checkedRunnable); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(RuntimeException.class); assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1); assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1); }
Example 6
Source File: RunnableRetryTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldReturnAfterOneAttemptAndIgnoreException() { willThrow(new HelloWorldException()).given(helloWorldService).sayHelloWorld(); RetryConfig config = RetryConfig.custom() .retryOnException(throwable -> Match(throwable).of( Case($(Predicates.instanceOf(HelloWorldException.class)), false), Case($(), true))) .build(); Retry retry = Retry.of("id", config); CheckedRunnable retryableRunnable = Retry .decorateCheckedRunnable(retry, helloWorldService::sayHelloWorld); Try<Void> result = Try.run(retryableRunnable); // because the exception should be rethrown immediately then(helloWorldService).should().sayHelloWorld(); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(HelloWorldException.class); assertThat(sleptTime).isEqualTo(0); }
Example 7
Source File: CircuitBreakerTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldDecorateCheckedConsumerAndReturnWithException() throws Throwable { CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.ofDefaults(); CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("testName"); CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); int numberOfBufferedCallsBefore = metrics.getNumberOfBufferedCalls(); CheckedConsumer<String> checkedConsumer = circuitBreaker .decorateCheckedConsumer((value) -> { throw new RuntimeException("BAM!"); }); Try<Void> result = Try.run(() -> checkedConsumer.accept("Tom")); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(RuntimeException.class); assertThat(numberOfBufferedCallsBefore).isEqualTo(0); assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1); assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1); assertThat(metrics.getNumberOfSuccessfulCalls()).isEqualTo(0); }
Example 8
Source File: RunnableRetryTest.java From resilience4j with Apache License 2.0 | 6 votes |
@Test public void shouldTakeIntoAccountBackoffFunction() { willThrow(new HelloWorldException()).given(helloWorldService).sayHelloWorld(); RetryConfig config = RetryConfig .custom() .intervalFunction(IntervalFunction.of(Duration.ofMillis(500), x -> x * x)) .build(); Retry retry = Retry.of("id", config); CheckedRunnable retryableRunnable = Retry .decorateCheckedRunnable(retry, helloWorldService::sayHelloWorld); Try.run(retryableRunnable); then(helloWorldService).should(times(3)).sayHelloWorld(); assertThat(sleptTime).isEqualTo( RetryConfig.DEFAULT_WAIT_DURATION + RetryConfig.DEFAULT_WAIT_DURATION * RetryConfig.DEFAULT_WAIT_DURATION); }
Example 9
Source File: RunnableRetryTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void testDecorateRunnable() { willThrow(new HelloWorldException()).given(helloWorldService).sayHelloWorld(); Retry retry = Retry.ofDefaults("id"); Runnable runnable = Retry.decorateRunnable(retry, helloWorldService::sayHelloWorld); Try<Void> result = Try.run(runnable::run); then(helloWorldService).should(times(3)).sayHelloWorld(); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(HelloWorldException.class); assertThat(sleptTime).isEqualTo(RetryConfig.DEFAULT_WAIT_DURATION * 2); }
Example 10
Source File: RunnableRetryTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void shouldReturnAfterThreeAttempts() { willThrow(new HelloWorldException()).given(helloWorldService).sayHelloWorld(); Retry retry = Retry.ofDefaults("id"); CheckedRunnable retryableRunnable = Retry .decorateCheckedRunnable(retry, helloWorldService::sayHelloWorld); Try<Void> result = Try.run(retryableRunnable); then(helloWorldService).should(times(3)).sayHelloWorld(); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(HelloWorldException.class); assertThat(sleptTime).isEqualTo(RetryConfig.DEFAULT_WAIT_DURATION * 2); }
Example 11
Source File: BulkheadTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void shouldReturnFailureWithRuntimeException() { BulkheadConfig config = BulkheadConfig.custom().maxConcurrentCalls(2).build(); Bulkhead bulkhead = Bulkhead.of("test", config); bulkhead.tryAcquirePermission(); CheckedRunnable checkedRunnable = Bulkhead.decorateCheckedRunnable(bulkhead, () -> { throw new RuntimeException("BAM!"); }); Try result = Try.run(checkedRunnable); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(RuntimeException.class); assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1); }
Example 12
Source File: BulkheadTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void shouldDecorateCheckedConsumerAndReturnWithException() throws Throwable { Bulkhead bulkhead = Bulkhead.of("test", config); CheckedConsumer<String> checkedConsumer = Bulkhead .decorateCheckedConsumer(bulkhead, (value) -> { throw new RuntimeException("BAM!"); }); Try<Void> result = Try.run(() -> checkedConsumer.accept("Tom")); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(RuntimeException.class); assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1); }
Example 13
Source File: BulkheadTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void shouldDecorateConsumerAndReturnWithException() throws Throwable { Bulkhead bulkhead = Bulkhead.of("test", config); Consumer<String> consumer = Bulkhead.decorateConsumer(bulkhead, (value) -> { throw new RuntimeException("BAM!"); }); Try<Void> result = Try.run(() -> consumer.accept("Tom")); assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(RuntimeException.class); assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1); }
Example 14
Source File: CircuitBreakerTest.java From resilience4j with Apache License 2.0 | 5 votes |
@Test public void shouldReturnFailureWithCircuitBreakerOpenException() { // Given CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() .slidingWindowSize(2) .permittedNumberOfCallsInHalfOpenState(2) .failureRateThreshold(50) .waitDurationInOpenState(Duration.ofMillis(1000)) .build(); CircuitBreaker circuitBreaker = CircuitBreaker.of("testName", circuitBreakerConfig); CheckedRunnable checkedRunnable = circuitBreaker.decorateCheckedRunnable(() -> { throw new RuntimeException("BAM!"); }); // When circuitBreaker.onError(0, TimeUnit.NANOSECONDS, new RuntimeException()); circuitBreaker.onError(0, TimeUnit.NANOSECONDS, new RuntimeException()); // Then assertThat(circuitBreaker.getState()).isEqualTo(CircuitBreaker.State.OPEN); CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics(); assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(2); assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(2); // When Try result = Try.run(checkedRunnable); // Then assertThat(result.isFailure()).isTrue(); assertThat(result.failed().get()).isInstanceOf(CallNotPermittedException.class); }
Example 15
Source File: BackendCService.java From resilience4j-spring-boot2-demo with Apache License 2.0 | 5 votes |
@Override @Bulkhead(name = BACKEND_C, type = Type.THREADPOOL) @TimeLimiter(name = BACKEND_C) @CircuitBreaker(name = BACKEND_C, fallbackMethod = "futureFallback") public CompletableFuture<String> futureTimeout() { Try.run(() -> Thread.sleep(5000)); return CompletableFuture.completedFuture("Hello World from backend A"); }
Example 16
Source File: BackendAService.java From resilience4j-spring-boot2-demo with Apache License 2.0 | 5 votes |
@Override @Bulkhead(name = BACKEND_A, type = Type.THREADPOOL) @TimeLimiter(name = BACKEND_A) @CircuitBreaker(name = BACKEND_A, fallbackMethod = "futureFallback") public CompletableFuture<String> futureTimeout() { Try.run(() -> Thread.sleep(5000)); return CompletableFuture.completedFuture("Hello World from backend A"); }
Example 17
Source File: HelpPopupStepDefinitions.java From IridiumApplicationTesting with MIT License | 4 votes |
/** * Displays a message in a window above the browser. Only works * where Java is able to create a UI. * * @param message The message to display * @param width The width of the help popup * @param height The height of the help popup * @param fontSize The font size * @param timeAlias indicates that the time value is aliased * @param time The time to show the message for * @param ignoreErrors Add this text to ignore any errors */ @Then("I display the help message \"(.*?)\"" + "(?: in a window sized \"(.*?)x(.*?)\")?" + "(?: with font size \"(.*?)\")?" + "(?: for( alias)? \"(.*?)\" seconds)?( ignoring errors)?") public void displayMessage( final String message, final String width, final String height, final String fontSize, final String timeAlias, final String time, final String ignoreErrors) { try { final String timeValue = StringUtils.isBlank(time) ? DEFAULT_TIME_TO_DISPLAY.toString() : autoAliasUtils.getValue( time, StringUtils.isNotBlank(timeAlias), State.getFeatureStateForThread()); final Integer fixedTime = NumberUtils.toInt(timeValue, DEFAULT_TIME_TO_DISPLAY); final Integer fixedWidth = NumberUtils.toInt(width, MESSAGE_WIDTH); final Integer fixedHeight = NumberUtils.toInt(height, MESSAGE_HEIGHT); final Integer fixedFont = NumberUtils.toInt(fontSize, MESSAGE_FONT_SIZE); final JFrame frame = new JFrame(); frame.setAlwaysOnTop(true); frame.setUndecorated(true); frame.setSize(fixedWidth, fixedHeight); /* Center the window */ frame.setLocationRelativeTo(null); /* Create the message */ final JLabel label = new JLabel( "<html><p style='padding: 20px'>" + message + "</p></html>"); final Font labelFont = label.getFont(); label.setFont(new Font(labelFont.getName(), Font.PLAIN, fixedFont)); label.setHorizontalAlignment(JLabel.CENTER); label.setVerticalAlignment(JLabel.CENTER); label.setOpaque(true); label.setMaximumSize(new Dimension(fixedWidth, fixedHeight)); label.setBackground(MESSAGE_BACKGROUND_COLOUR); label.setBorder(BorderFactory.createLineBorder(Color.BLACK, BORDER_THICKNESS)); frame.getContentPane().add(label); /* Display the message */ frame.setVisible(true); Try.run(() -> Thread.sleep(fixedTime * Constants.MILLISECONDS_PER_SECOND)); /* Close the window */ frame.setVisible(false); frame.dispose(); } catch (final Exception ex) { LOGGER.error("Could not display popup", ex); if (!StringUtils.isEmpty(ignoreErrors)) { throw ex; } } }
Example 18
Source File: BackendBService.java From resilience4j-spring-boot2-demo with Apache License 2.0 | 4 votes |
@Override public CompletableFuture<String> futureTimeout() { Try.run(() -> Thread.sleep(5000)); return CompletableFuture.completedFuture("Hello World from backend A"); }
Example 19
Source File: RegisteringOverdueCheckout.java From library with MIT License | 4 votes |
private Try<Void> publish(OverdueCheckoutRegistered event) { return Try.run(() -> patronRepository.publish(event)); }
Example 20
Source File: ExpiringHolds.java From library with MIT License | 4 votes |
private Try<Void> publish(PatronEvent.BookHoldExpired event) { return Try.run(() -> patronRepository.publish(event)); }