37
37
import java .util .List ;
38
38
import java .util .Objects ;
39
39
import java .util .Set ;
40
+ import java .util .function .Supplier ;
40
41
import java .util .regex .Pattern ;
41
42
import java .util .spi .ToolProvider ;
42
43
import java .util .stream .Collectors ;
@@ -235,18 +236,49 @@ public List<String> executeAndGetOutput() {
235
236
return saveOutput ().execute ().getOutput ();
236
237
}
237
238
239
+ private static class BadResultException extends RuntimeException {
240
+ BadResultException (Result v ) {
241
+ value = v ;
242
+ }
243
+
244
+ Result getValue () {
245
+ return value ;
246
+ }
247
+
248
+ private final Result value ;
249
+ }
250
+
238
251
/*
239
252
* Repeates command "max" times and waits for "wait" seconds between each
240
253
* execution until command returns expected error code.
241
254
*/
242
255
public Result executeAndRepeatUntilExitCode (int expectedCode , int max , int wait ) {
243
- Result result ;
256
+ try {
257
+ return tryRunMultipleTimes (() -> {
258
+ Result result = executeWithoutExitCodeCheck ();
259
+ if (result .getExitCode () != expectedCode ) {
260
+ throw new BadResultException (result );
261
+ }
262
+ return result ;
263
+ }, max , wait ).assertExitCodeIs (expectedCode );
264
+ } catch (BadResultException ex ) {
265
+ return ex .getValue ().assertExitCodeIs (expectedCode );
266
+ }
267
+ }
268
+
269
+ /*
270
+ * Repeates a "task" "max" times and waits for "wait" seconds between each
271
+ * execution until the "task" returns without throwing an exception.
272
+ */
273
+ public static <T > T tryRunMultipleTimes (Supplier <T > task , int max , int wait ) {
274
+ RuntimeException lastException = null ;
244
275
int count = 0 ;
245
276
246
277
do {
247
- result = executeWithoutExitCodeCheck ();
248
- if (result .getExitCode () == expectedCode ) {
249
- return result ;
278
+ try {
279
+ return task .get ();
280
+ } catch (RuntimeException ex ) {
281
+ lastException = ex ;
250
282
}
251
283
252
284
try {
@@ -258,7 +290,14 @@ public Result executeAndRepeatUntilExitCode(int expectedCode, int max, int wait)
258
290
count ++;
259
291
} while (count < max );
260
292
261
- return result .assertExitCodeIs (expectedCode );
293
+ throw lastException ;
294
+ }
295
+
296
+ public static void tryRunMultipleTimes (Runnable task , int max , int wait ) {
297
+ tryRunMultipleTimes (() -> {
298
+ task .run ();
299
+ return null ;
300
+ }, max , wait );
262
301
}
263
302
264
303
public List <String > executeWithoutExitCodeCheckAndGetOutput () {
0 commit comments