import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
public class ApiBackup {
private static final int RETRY_INTERVAL = 5000; // Retry interval in milliseconds
private static final int MAX_RETRIES = 3;
private static final String BACKUP_DIR = "api_backups"; // Directory to store backups
public static void main(String[] args) throws InterruptedException, IOException {
// Create backup directory if it doesn't exist
File backupDir = new File(BACKUP_DIR);
if (!backupDir.exists()) {
backupDir.mkdirs();
}
// Example API endpoint configuration
List<Map<String, String>> apiEndpoints = new ArrayList<>();
apiEndpoints.add(Map.of("url", "https://api.example.com/endpoint1", "method", "GET"));
apiEndpoints.add(Map.of("url", "https://api.example.com/endpoint2", "method", "POST"));
apiEndpoints.add(Map.of("url", "https://api.example.com/endpoint3", "method", "GET"));
for (Map<String, String> endpoint : apiEndpoints) {
String url = endpoint.get("url");
String method = endpoint.get("method");
backupApiEndpoint(url, method);
}
}
public static void backupApiEndpoint(String url, String method) throws InterruptedException, IOException {
String filename = url.replace("://", "_").replace("/", "_") + "_" + System.currentTimeMillis() + ".json";
File outputFile = new File(BACKUP_DIR, filename);
for (int retry = 0; retry <= MAX_RETRIES; retry++) {
try {
// Make the API request
String response = makeApiRequest(url, method);
// Write the response to the file
try (FileWriter writer = new FileWriter(outputFile)) {
writer.write(response);
}
System.out.println("Successfully backed up: " + url + " to " + outputFile.getAbsolutePath());
return; // Exit the retry loop on success
} catch (IOException e) {
System.err.println("Backup failed for " + url + " (attempt " + (retry + 1) + "): " + e.getMessage());
if (retry < MAX_RETRIES) {
Thread.sleep(RETRY_INTERVAL); // Wait before retrying
} else {
System.err.println("Backup failed for " + url + " after " + MAX_RETRIES + " retries.");
}
}
}
}
private static String makeApiRequest(String url, String method) throws IOException {
try (URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection()) {
conn.setRequestMethod(method);
conn.setReadTimeout(10000); // 10 seconds timeout
conn.setConnectTimeout(5000); // 5 seconds timeout
int responseCode = conn.getResponseCode();
if (responseCode >= 200 && responseCode < 300) {
try (InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line).append("\n");
}
return response.toString();
}
} else {
throw new IOException("API request failed with response code: " + responseCode);
}
}
}
}
Add your comment