1. import java.io.*;
  2. import java.net.HttpURLConnection;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. import java.util.concurrent.ConcurrentHashMap;
  6. public class JsonBackup {
  7. private static final int MAX_REQUESTS_PER_MINUTE = 10; // Rate limit
  8. private static final ConcurrentHashMap<String, Long> requestTimestamps = new ConcurrentHashMap<>(); // Track request timestamps
  9. public static void backupJson(String url, String filenamePrefix) {
  10. try {
  11. // Rate limiting check
  12. long currentTime = System.currentTimeMillis();
  13. if (isRateLimited()) {
  14. System.out.println("Rate limit exceeded. Skipping " + url);
  15. return;
  16. }
  17. HttpURLConnection connection = getURLConnection(url);
  18. if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
  19. String jsonResponse = readResponse(connection);
  20. saveJsonToFile(jsonResponse, filenamePrefix);
  21. System.out.println("Backed up " + url + " to " + filenamePrefix + ".json");
  22. } else {
  23. System.out.println("Error backing up " + url + ". Status code: " + connection.getResponseCode());
  24. }
  25. connection.disconnect();
  26. } catch (IOException e) {
  27. System.err.println("Error backing up " + url + ": " + e.getMessage());
  28. }
  29. }
  30. private static HttpURLConnection getURLConnection(String url) throws IOException {
  31. return new HttpURLConnection(url).openConnection();
  32. }
  33. private static String readResponse(HttpURLConnection connection) throws IOException {
  34. try (InputStream inputStream = connection.getInputStream();
  35. BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
  36. StringBuilder sb = new StringBuilder();
  37. String line;
  38. while ((line = reader.readLine()) != null) {
  39. sb.append(line);
  40. }
  41. return sb.toString();
  42. }
  43. }
  44. private static void saveJsonToFile(String jsonResponse, String filenamePrefix) throws IOException {
  45. String filename = filenamePrefix + System.currentTimeMillis() + ".json"; //Unique filename
  46. try (FileWriter writer = new FileWriter(filename)) {
  47. writer.write(jsonResponse);
  48. }
  49. }
  50. private static boolean isRateLimited() {
  51. long now = System.currentTimeMillis();
  52. requestTimestamps.removeIf(timestamp -> timestamp < now - 60000); // Remove requests older than 1 minute (60000ms)
  53. int count = requestTimestamps.size();
  54. if (count >= MAX_REQUESTS_PER_MINUTE) {
  55. return true;
  56. }
  57. requestTimestamps.put(now, now + 60000); // Store timestamp for the next minute
  58. return false;
  59. }
  60. public static void main(String[] args) {
  61. // Example Usage
  62. String url1 = "https://rickandmortyapi.com/api/character";
  63. String url2 = "https://jsonplaceholder.typicode.com/todos/1";
  64. String filenamePrefix = "backup_";
  65. backupJson(url1, filenamePrefix);
  66. backupJson(url2, filenamePrefix);
  67. }
  68. }

Add your comment