3737import java .util .List ;
3838import java .util .Objects ;
3939import java .util .Set ;
40+ import java .util .function .Supplier ;
4041import java .util .regex .Pattern ;
4142import java .util .spi .ToolProvider ;
4243import java .util .stream .Collectors ;
@@ -250,18 +251,49 @@ public List<String> executeAndGetOutput() {
250251 return saveOutput ().execute ().getOutput ();
251252 }
252253
254+ private static class BadResultException extends RuntimeException {
255+ BadResultException (Result v ) {
256+ value = v ;
257+ }
258+
259+ Result getValue () {
260+ return value ;
261+ }
262+
263+ private final Result value ;
264+ }
265+
253266 /*
254267 * Repeates command "max" times and waits for "wait" seconds between each
255268 * execution until command returns expected error code.
256269 */
257270 public Result executeAndRepeatUntilExitCode (int expectedCode , int max , int wait ) {
258- Result result ;
271+ try {
272+ return tryRunMultipleTimes (() -> {
273+ Result result = executeWithoutExitCodeCheck ();
274+ if (result .getExitCode () != expectedCode ) {
275+ throw new BadResultException (result );
276+ }
277+ return result ;
278+ }, max , wait ).assertExitCodeIs (expectedCode );
279+ } catch (BadResultException ex ) {
280+ return ex .getValue ().assertExitCodeIs (expectedCode );
281+ }
282+ }
283+
284+ /*
285+ * Repeates a "task" "max" times and waits for "wait" seconds between each
286+ * execution until the "task" returns without throwing an exception.
287+ */
288+ public static <T > T tryRunMultipleTimes (Supplier <T > task , int max , int wait ) {
289+ RuntimeException lastException = null ;
259290 int count = 0 ;
260291
261292 do {
262- result = executeWithoutExitCodeCheck ();
263- if (result .getExitCode () == expectedCode ) {
264- return result ;
293+ try {
294+ return task .get ();
295+ } catch (RuntimeException ex ) {
296+ lastException = ex ;
265297 }
266298
267299 try {
@@ -273,7 +305,14 @@ public Result executeAndRepeatUntilExitCode(int expectedCode, int max, int wait)
273305 count ++;
274306 } while (count < max );
275307
276- return result .assertExitCodeIs (expectedCode );
308+ throw lastException ;
309+ }
310+
311+ public static void tryRunMultipleTimes (Runnable task , int max , int wait ) {
312+ tryRunMultipleTimes (() -> {
313+ task .run ();
314+ return null ;
315+ }, max , wait );
277316 }
278317
279318 public List <String > executeWithoutExitCodeCheckAndGetOutput () {
0 commit comments