1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.concurrent.Executors;
  4. import java.util.concurrent.ScheduledExecutorService;
  5. import java.util.concurrent.TimeUnit;
  6. public class QueryStringWatcher {
  7. private static final int DEFAULT_RETRY_INTERVAL = 2; // seconds
  8. private final int retryInterval;
  9. private final Map<String, String> lastQueryString;
  10. public QueryStringWatcher(int retryInterval) {
  11. this.retryInterval = retryInterval;
  12. this.lastQueryString = new HashMap<>();
  13. }
  14. public void watchQueryString(String queryString) {
  15. // Store the current query string
  16. lastQueryString.put(queryString);
  17. // Simulate a background task that checks for changes
  18. ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
  19. scheduler.scheduleAtFixedRate(() -> {
  20. String currentQueryString = getQueryString();
  21. if (!currentQueryString.equals(lastQueryString.get(queryString))) {
  22. System.out.println("Query string changed: " + currentQueryString);
  23. lastQueryString.put(queryString, currentQueryString);
  24. }
  25. }, 0, retryInterval, TimeUnit.SECONDS);
  26. }
  27. private String getQueryString() {
  28. // Placeholder for getting the query string. Replace with your actual implementation.
  29. // This simulates reading from a request object or environment variable.
  30. // Example: Read from System.getProperty("query.string")
  31. String queryString = System.getProperty("query.string");
  32. if (queryString == null) {
  33. queryString = "default"; //Default value if not found
  34. }
  35. return queryString;
  36. }
  37. public static void main(String[] args) throws InterruptedException {
  38. // Example Usage
  39. QueryStringWatcher watcher = new QueryStringWatcher(5); // Retry every 5 seconds
  40. // Simulate changes to the query string
  41. String initialQueryString = "initial=value";
  42. watcher.watchQueryString(initialQueryString);
  43. Thread.sleep(2000); // Wait 2 seconds
  44. watcher.watchQueryString("updated=value"); // Simulate a change
  45. Thread.sleep(2000);
  46. watcher.watchQueryString("updated2=value");
  47. }
  48. }

Add your comment