1. import java.io.IOException;
  2. import java.nio.file.Files;
  3. import java.nio.file.Path;
  4. import java.nio.file.Paths;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. public class FormDataArchiver {
  8. private static final String ARCHIVE_FILE = "form_data_archive.txt";
  9. private static final int MAX_RETRIES = 3;
  10. private static final long RETRY_DELAY_MS = 1000; // 1 second
  11. public static void main(String[] args) {
  12. // Simulate form data (replace with actual form data retrieval)
  13. Map<String, String> formData = new HashMap<>();
  14. formData.put("name", "John Doe");
  15. formData.put("email", "john.doe@example.com");
  16. formData.put("phone", "555-123-4567");
  17. archiveFormData(formData);
  18. }
  19. public static void archiveFormData(Map<String, String> formData) {
  20. int retryCount = 0;
  21. while (retryCount <= MAX_RETRIES) {
  22. try {
  23. if (writeFormDataToArchive(formData)) {
  24. System.out.println("Form data archived successfully.");
  25. return;
  26. } else {
  27. retryCount++;
  28. if (retryCount <= MAX_RETRIES) {
  29. System.out.println("Archive failed. Retrying in " + RETRY_DELAY_MS + "ms...");
  30. Thread.sleep(RETRY_DELAY_MS);
  31. } else {
  32. System.err.println("Archive failed after " + MAX_RETRIES + " retries.");
  33. return;
  34. }
  35. }
  36. } catch (IOException e) {
  37. System.err.println("Error archiving form data: " + e.getMessage());
  38. retryCount++;
  39. if (retryCount <= MAX_RETRIES) {
  40. System.out.println("Retrying in " + RETRY_DELAY_MS + "ms...");
  41. try {
  42. Thread.sleep(RETRY_DELAY_MS);
  43. } catch (InterruptedException ie) {
  44. Thread.currentThread().interrupt(); // Restore interrupted state
  45. }
  46. } else {
  47. System.err.println("Archive failed after " + MAX_RETRIES + " retries.");
  48. return;
  49. }
  50. }
  51. }
  52. }
  53. private static boolean writeFormDataToArchive(Map<String, String> formData) throws IOException {
  54. try (java.io.BufferedWriter writer = Files.newBufferedWriter(Paths.get(ARCHIVE_FILE))) {
  55. for (Map.Entry<String, String> entry : formData.entrySet()) {
  56. writer.write(entry.getKey() + ":" + entry.getValue() + "\n");
  57. }
  58. return true; // Indicate success
  59. }
  60. }
  61. }

Add your comment