@Test public void shouldConsumeIgnoredErrorEvent() { CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom() .recordFailure(throwable -> Match(throwable).of( Case($(instanceOf(WebServiceException.class)), true), Case($(), false))) .build(); circuitBreaker = CircuitBreaker.of("test", circuitBreakerConfig); circuitBreaker.getEventPublisher() .onIgnoredError(this::logEventType) ; circuitBreaker.onError(1000, new IOException("BAM!")); then(logger).should(times(1)).info("IGNORED_ERROR"); }
private static Optional<String> reveal(ConfigurationContext context, String captured) { return context.getSecretSources().stream() .map(source -> unchecked(() -> source.reveal(captured)).apply()) .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)) .findFirst(); }
private GeneratedItems generateFromScript(String script, JenkinsJobManagement management) { return unchecked(() -> Try(() -> new JenkinsDslScriptLoader(management).runScript(script)) .getOrElseThrow(t -> new ConfiguratorException(this, "Failed to execute script with hash " + script.hashCode(), t))).apply(); }
/** * Maps the cause to a new exception if this is a {@code Failure} or returns this instance if this is a {@code Success}. * <p> * If none of the given cases matches the cause, the same {@code Failure} is returned. * * @param cases A not necessarily exhaustive sequence of cases that will be matched against a cause. * @return A new {@code Try} if this is a {@code Failure}, otherwise this. */ @GwtIncompatible @SuppressWarnings({ "unchecked", "varargs" }) default Try<T> mapFailure(Match.Case<? extends Throwable, ? extends Throwable>... cases) { if (isSuccess()) { return this; } else { final Option<Throwable> x = Match(getCause()).option(cases); return x.isEmpty() ? this : failure(x.get()); } }
ErrorTally(EventBusInterface eventBusInterface) { this.eventBusInterface = eventBusInterface; this.errors = List(); }
/** * Maps the cause to a new exception if this is a {@code Failure} or returns this instance if this is a {@code Success}. * <p> * If none of the given cases matches the cause, the same {@code Failure} is returned. * * @param cases A not necessarily exhaustive sequence of cases that will be matched against a cause. * @return A new {@code Try} if this is a {@code Failure}, otherwise this. */ @GwtIncompatible @SuppressWarnings({ "unchecked", "varargs" }) default Try<T> mapFailure(Match.Case<? extends Throwable, ? extends Throwable>... cases) { if (isSuccess()) { return this; } else { final Option<Throwable> x = Match(getCause()).option(cases); return x.isEmpty() ? this : failure(x.get()); } }
private String getScriptFromSource(CNode source, ConfigurationContext context, Configurator<ScriptSource> configurator) { return unchecked(() -> Try(() -> configurator.configure(source, context)) .getOrElseThrow(t -> new ConfiguratorException(this, "Failed to retrieve job-dsl script", t)) .getScript()).apply(); } }
private static List<String> convertArguments(Object[] arguments) { return List(arguments).map(StepArgumentWriter::readableFormOf).asJava(); }
@Test public void waitForPermissionWithInterruption() throws Exception { when(limit.getPermission(config.getTimeoutDuration())) .then(invocation -> { LockSupport.parkNanos(5_000_000_000L); return null; }); AtomicBoolean wasInterrupted = new AtomicBoolean(true); Thread thread = new Thread(() -> { wasInterrupted.set(false); Throwable cause = Try.run(() -> RateLimiter.waitForPermission(limit)) .getCause(); Boolean interrupted = Match(cause).of( Case($(instanceOf(IllegalStateException.class)), true) ); wasInterrupted.set(interrupted); }); thread.setDaemon(true); thread.start(); await() .atMost(5, TimeUnit.SECONDS) .until(wasInterrupted::get, equalTo(false)); thread.interrupt(); await() .atMost(5, TimeUnit.SECONDS) .until(wasInterrupted::get, equalTo(true)); }
private CNode getActualValue(CNode config, ConfigurationContext context) { return unchecked(() -> config.asMapping().entrySet().stream().findFirst()).apply() .map(entry -> { Mapping mapping = new Mapping(); mapping.put(entry.getKey(), revealSourceOrGetValue(entry, context)); return (CNode) mapping; }).orElse(config); }
private Map<String, List<TestOutcome>> groupByTestCase(TestOutcomes testOutcomes) { Map<String, List<TestOutcome>> groupedTestOutcomes = new HashMap<>(); for (TestOutcome outcome : testOutcomes.getOutcomes()) { String testCaseName = StringUtils.isNotEmpty(outcome.getTestCaseName()) ? outcome.getTestCaseName() : outcome.getStoryTitle(); List<TestOutcome> currentOutcomes = groupedTestOutcomes.getOrDefault(testCaseName, List()); groupedTestOutcomes.put(testCaseName, currentOutcomes.append(outcome)); } return groupedTestOutcomes; }
@Test public void shouldReturnAfterOneAttemptAndIgnoreException() { // Given the HelloWorldService throws an exception BDDMockito.given(helloWorldService.returnHelloWorld()).willThrow(new WebServiceException("BAM!")); // Create a Retry with default configuration RetryConfig config = RetryConfig.custom() .retryOnException(throwable -> API.Match(throwable).of( API.Case($(Predicates.instanceOf(WebServiceException.class)), false), API.Case($(), true))) .build(); Retry retry = Retry.of("id", config); // Decorate the invocation of the HelloWorldService CheckedFunction0<String> retryableSupplier = Retry .decorateCheckedSupplier(retry, helloWorldService::returnHelloWorld); // When Try<String> result = Try.of(retryableSupplier); // Then the helloWorldService should be invoked only once, because the exception should be rethrown immediately. BDDMockito.then(helloWorldService).should(Mockito.times(1)).returnHelloWorld(); // and the result should be a failure assertThat(result.isFailure()).isTrue(); // and the returned exception should be of type RuntimeException assertThat(result.failed().get()).isInstanceOf(WebServiceException.class); assertThat(sleptTime).isEqualTo(0); }
private String revealSourceOrGetValue(Map.Entry<String, CNode> entry, ConfigurationContext context) { String value = unchecked(() -> entry.getValue().asScalar().getValue()).apply(); return SecretSourceResolver.resolve(context, value); }
@Test public void shouldReturnAfterOneAttemptAndIgnoreException() { // Given the HelloWorldService throws an exception BDDMockito.willThrow(new WebServiceException("BAM!")).given(helloWorldService).sayHelloWorld(); // Create a Retry with default configuration RetryConfig config = RetryConfig.custom() .retryOnException(throwable -> Match(throwable).of( Case($(Predicates.instanceOf(WebServiceException.class)), false), Case($(), true))) .build(); Retry retry = Retry.of("id", config); // Decorate the invocation of the HelloWorldService CheckedRunnable retryableRunnable = Retry.decorateCheckedRunnable(retry, helloWorldService::sayHelloWorld); // When Try<Void> result = Try.run(retryableRunnable); // Then the helloWorldService should be invoked only once, because the exception should be rethrown immediately. BDDMockito.then(helloWorldService).should(Mockito.times(1)).sayHelloWorld(); // and the result should be a failure Assertions.assertThat(result.isFailure()).isTrue(); // and the returned exception should be of type RuntimeException Assertions.assertThat(result.failed().get()).isInstanceOf(WebServiceException.class); Assertions.assertThat(sleptTime).isEqualTo(0); }
@Cacheable("availableVersions") public List<LyrebirdVersion> getAllVersions() { final PathMatchingResourcePatternResolver versionsResourcesResolver = new PathMatchingResourcePatternResolver(); try { final Resource[] versionResources = versionsResourcesResolver.getResources(VERSIONS_PATTERN); return Arrays.stream(versionResources) .map(unchecked(Resource::getInputStream)) .map(unchecked(is -> objectMapper.readValue(is, LyrebirdVersion.class))) .sorted(Comparator.comparing(LyrebirdVersion::getBuildVersion).reversed()) .collect(Collectors.toList()); } catch (final IOException e) { throw new IllegalStateException("Can not load releases!", e); } }
@Test public void shouldConsumeIgnoredErrorEvent() { given(helloWorldService.returnHelloWorld()) .willThrow(new WebServiceException("BAM!")); RetryConfig retryConfig = RetryConfig.custom() .retryOnException(throwable -> Match(throwable).of( Case($(instanceOf(WebServiceException.class)), false), Case($(), true))) .build(); retry = Retry.of("testName", retryConfig); retry.getEventPublisher() .onIgnoredError(event -> logger.info(event.getEventType().toString())); Try.ofSupplier(Retry.decorateSupplier(retry, helloWorldService::returnHelloWorld)); then(logger).should(times(1)).info("IGNORED_ERROR"); then(helloWorldService).should(times(1)).returnHelloWorld(); }
/** * Uploads the given media files to Twitter * * @param twitter The twitter instance to use for uploading * @param attachments The media files to upload * * @return The uploaded media files Twitter-side ids */ private static List<Long> uploadMedias(final Twitter twitter, final List<File> attachments) { LOG.debug("Uploading media attachments {}", attachments); return attachments.stream() .map(unchecked((CheckedFunction1<File, UploadedMedia>) twitter::uploadMedia)) .map(UploadedMedia::getMediaId) .collect(Collectors.toList()); }
.ringBufferSizeInHalfOpenState(2) .waitDurationInOpenState(Duration.ofMillis(1000)) .recordFailure(throwable -> Match(throwable).of( Case($(instanceOf(WebServiceException.class)), true), Case($(), false))) .build(); CircuitBreaker circuitBreaker = CircuitBreaker.of("testName", circuitBreakerConfig);
private static Optional<String> reveal(ConfigurationContext context, String captured) { return context.getSecretSources().stream() .map(source -> unchecked(() -> source.reveal(captured)).apply()) .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)) .findFirst(); }
@Test public void shouldConsumeIgnoredErrorEvent() { given(helloWorldService.returnHelloWorld()) .willThrow(new WebServiceException("BAM!")); RetryConfig retryConfig = RetryConfig.custom() .retryOnException(throwable -> Match(throwable).of( Case($(instanceOf(WebServiceException.class)), false), Case($(), true))) .build(); retry = AsyncRetry.of("testName", retryConfig); retry.getEventPublisher() .onIgnoredError(event -> logger.info(event.getEventType().toString())); Try.of(() -> awaitResult(retry.executeCompletionStage(scheduler, () -> helloWorldService.returnHelloWorld()))); then(logger).should(times(1)).info("IGNORED_ERROR"); then(helloWorldService).should(times(1)).returnHelloWorld(); }