You can use while. You're checking if the alert is present, and each time it is there, you resolve it according to that boolean value that you give it. When there is no new alert anymore, it will break and continue on.
public static void resolveAllAlerts(WebDriver driver, int timeout, boolean accept) {
while (isAlertPresent(driver, timeout)) {
resolveAlert(driver, accept);
}
}
private static boolean isAlertPresent(WebDriver driver, int timeout) {
try {
Alert a = new WebDriverWait(driver, timeout).until(ExpectedConditions.alertIsPresent());
if (a != null) {
return true;
} else {
throw new TimeoutException();
}
} catch (TimeoutException e) {
// log the exception;
return false;
}
}
private static void resolveAlert(WebDriver driver, boolean accept) {
if (accept) {
driver.switchTo().alert().accept();
} else {
driver.switchTo().alert().dismiss();
}
}