1. import java.util.Collection;
  2. import java.util.HashSet;
  3. import java.util.Set;
  4. public class CollectionGuard {
  5. private final Set<String> guardedCollections = new HashSet<>();
  6. private boolean dryRunMode = false;
  7. public CollectionGuard() {
  8. // Add collections to be guarded. Can be dynamically updated.
  9. }
  10. public void addCollection(String collectionName) {
  11. guardedCollections.add(collectionName);
  12. }
  13. public void setDryRunMode(boolean dryRunMode) {
  14. this.dryRunMode = dryRunMode;
  15. }
  16. public void executeTask(String collectionName, Runnable task) {
  17. if (dryRunMode) {
  18. System.out.println("Dry run: Would execute task on collection: " + collectionName);
  19. return;
  20. }
  21. if (!guardedCollections.contains(collectionName)) {
  22. System.out.println("Collection '" + collectionName + "' is not guarded. Skipping.");
  23. return;
  24. }
  25. try {
  26. task.run(); // Execute the task on the collection
  27. } catch (Exception e) {
  28. System.err.println("Error executing task on collection '" + collectionName + "': " + e.getMessage());
  29. e.printStackTrace();
  30. }
  31. }
  32. public static void main(String[] args) {
  33. CollectionGuard guard = new CollectionGuard();
  34. guard.addCollection("myCollection");
  35. // Example task
  36. Runnable myTask = () -> {
  37. System.out.println("Executing task on myCollection");
  38. };
  39. guard.setDryRunMode(false);
  40. guard.executeTask("myCollection", myTask);
  41. guard.setDryRunMode(true);
  42. guard.executeTask("myCollection", myTask);
  43. guard.executeTask("anotherCollection", myTask); // should skip
  44. }
  45. }

Add your comment