import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public class CookieBootstrapper {
private final Path scriptPath;
private final int retryCount;
private final long retryDelayMillis;
private final AtomicBoolean bootstrapped = new AtomicBoolean(false);
public CookieBootstrapper(Path scriptPath, int retryCount, long retryDelayMillis) {
this.scriptPath = scriptPath;
this.retryCount = retryCount;
this.retryDelayMillis = retryDelayMillis;
}
public void bootstrap() throws IOException {
for (int i = 0; i < retryCount; i++) {
try {
executeScript();
bootstrapped.set(true);
return; // Success, exit loop
} catch (IOException e) {
if (i == retryCount - 1) {
throw e; // Re-throw on last retry
}
System.err.println("Bootstrap failed (attempt " + (i + 1) + "): " + e.getMessage());
try {
Thread.sleep(retryDelayMillis);
} catch (InterruptedException e2) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted during retry", e2);
}
}
}
}
private void executeScript() throws IOException {
// Read the script file
String scriptContent = new String(Files.readAllBytes(scriptPath));
// Execute the script (replace with your actual execution logic)
System.out.println("Executing script: " + scriptPath);
// Example: Run the script using a shell command. Important: sanitize input!
// ProcessBuilder pb = new ProcessBuilder("bash", "-c", scriptContent);
// Process p = pb.start();
// p.waitFor();
//Simulate success
System.out.println("Script executed successfully.");
}
public boolean isBootstrapped() {
return bootstrapped.get();
}
public static void main(String[] args) throws IOException {
Path scriptPath = Paths.get("cookie_script.sh"); // Replace with your script path
int retryCount = 3;
long retryDelayMillis = 1000;
// Create a dummy script for testing
String scriptContent = "echo 'Running cookie bootstrap script' > /tmp/cookie_boot_test.txt";
Files.write(scriptPath, scriptContent.getBytes());
CookieBootstrapper bootstrapper = new CookieBootstrapper(scriptPath, retryCount, retryDelayMillis);
try {
bootstrapper.bootstrap();
if (bootstrapper.isBootstrapped()) {
System.out.println("Cookie bootstrap completed successfully.");
} else {
System.err.println("Cookie bootstrap failed after multiple retries.");
}
} catch (IOException e) {
System.err.println("Bootstrap failed permanently: " + e.getMessage());
} finally {
// Clean up the dummy script
try {
Files.deleteIfExists(scriptPath);
} catch (IOException e) {
System.err.println("Error deleting dummy script: " + e.getMessage());
}
}
}
}
Add your comment