import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class FormDataArchiver {
private static final String ARCHIVE_FILE = "form_data_archive.txt";
private static final int MAX_RETRIES = 3;
private static final long RETRY_DELAY_MS = 1000; // 1 second
public static void main(String[] args) {
// Simulate form data (replace with actual form data retrieval)
Map<String, String> formData = new HashMap<>();
formData.put("name", "John Doe");
formData.put("email", "john.doe@example.com");
formData.put("phone", "555-123-4567");
archiveFormData(formData);
}
public static void archiveFormData(Map<String, String> formData) {
int retryCount = 0;
while (retryCount <= MAX_RETRIES) {
try {
if (writeFormDataToArchive(formData)) {
System.out.println("Form data archived successfully.");
return;
} else {
retryCount++;
if (retryCount <= MAX_RETRIES) {
System.out.println("Archive failed. Retrying in " + RETRY_DELAY_MS + "ms...");
Thread.sleep(RETRY_DELAY_MS);
} else {
System.err.println("Archive failed after " + MAX_RETRIES + " retries.");
return;
}
}
} catch (IOException e) {
System.err.println("Error archiving form data: " + e.getMessage());
retryCount++;
if (retryCount <= MAX_RETRIES) {
System.out.println("Retrying in " + RETRY_DELAY_MS + "ms...");
try {
Thread.sleep(RETRY_DELAY_MS);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // Restore interrupted state
}
} else {
System.err.println("Archive failed after " + MAX_RETRIES + " retries.");
return;
}
}
}
}
private static boolean writeFormDataToArchive(Map<String, String> formData) throws IOException {
try (java.io.BufferedWriter writer = Files.newBufferedWriter(Paths.get(ARCHIVE_FILE))) {
for (Map.Entry<String, String> entry : formData.entrySet()) {
writer.write(entry.getKey() + ":" + entry.getValue() + "\n");
}
return true; // Indicate success
}
}
}
Add your comment