import java.io.*;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class JsonBackup {
private static final int MAX_REQUESTS_PER_MINUTE = 10; // Rate limit
private static final ConcurrentHashMap<String, Long> requestTimestamps = new ConcurrentHashMap<>(); // Track request timestamps
public static void backupJson(String url, String filenamePrefix) {
try {
// Rate limiting check
long currentTime = System.currentTimeMillis();
if (isRateLimited()) {
System.out.println("Rate limit exceeded. Skipping " + url);
return;
}
HttpURLConnection connection = getURLConnection(url);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
String jsonResponse = readResponse(connection);
saveJsonToFile(jsonResponse, filenamePrefix);
System.out.println("Backed up " + url + " to " + filenamePrefix + ".json");
} else {
System.out.println("Error backing up " + url + ". Status code: " + connection.getResponseCode());
}
connection.disconnect();
} catch (IOException e) {
System.err.println("Error backing up " + url + ": " + e.getMessage());
}
}
private static HttpURLConnection getURLConnection(String url) throws IOException {
return new HttpURLConnection(url).openConnection();
}
private static String readResponse(HttpURLConnection connection) throws IOException {
try (InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
}
private static void saveJsonToFile(String jsonResponse, String filenamePrefix) throws IOException {
String filename = filenamePrefix + System.currentTimeMillis() + ".json"; //Unique filename
try (FileWriter writer = new FileWriter(filename)) {
writer.write(jsonResponse);
}
}
private static boolean isRateLimited() {
long now = System.currentTimeMillis();
requestTimestamps.removeIf(timestamp -> timestamp < now - 60000); // Remove requests older than 1 minute (60000ms)
int count = requestTimestamps.size();
if (count >= MAX_REQUESTS_PER_MINUTE) {
return true;
}
requestTimestamps.put(now, now + 60000); // Store timestamp for the next minute
return false;
}
public static void main(String[] args) {
// Example Usage
String url1 = "https://rickandmortyapi.com/api/character";
String url2 = "https://jsonplaceholder.typicode.com/todos/1";
String filenamePrefix = "backup_";
backupJson(url1, filenamePrefix);
backupJson(url2, filenamePrefix);
}
}
Add your comment