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 EnvVariableFilter {
  7. private final Map<String, String> filteredEnvVars = new HashMap<>();
  8. private final String[] variablesToFilter;
  9. private final long retryIntervalMillis;
  10. private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
  11. public EnvVariableFilter(String[] variablesToFilter, long retryIntervalMillis) {
  12. this.variablesToFilter = variablesToFilter;
  13. this.retryIntervalMillis = retryIntervalMillis;
  14. }
  15. public void initialize() {
  16. for (String var : variablesToFilter) {
  17. try {
  18. String value = System.getenv(var);
  19. if (value != null && !value.isEmpty()) {
  20. filteredEnvVars.put(var, value);
  21. }
  22. } catch (NullPointerException e) {
  23. // Handle potential null pointer exceptions
  24. System.err.println("Variable " + var + " not found.");
  25. }
  26. }
  27. startRetryScheduler();
  28. }
  29. private void startRetryScheduler() {
  30. for (String var : variablesToFilter) {
  31. scheduler.scheduleAtFixedRate(() -> {
  32. try {
  33. String value = System.getenv(var);
  34. if (value != null && !value.isEmpty()) {
  35. filteredEnvVars.put(var, value);
  36. } else {
  37. System.err.println("Variable " + var + " not found (retry).");
  38. }
  39. } catch (NullPointerException e) {
  40. System.err.println("Variable " + var + " not found (retry).");
  41. }
  42. }, retryIntervalMillis, retryIntervalMillis, TimeUnit.MILLISECONDS);
  43. }
  44. }
  45. public Map<String, String> getFilteredEnvVars() {
  46. return new HashMap<>(filteredEnvVars); // Return a copy to prevent external modification
  47. }
  48. public void stop() {
  49. scheduler.shutdown();
  50. try {
  51. scheduler.awaitTermination(5, TimeUnit.SECONDS); // Give tasks time to finish
  52. } catch (InterruptedException e) {
  53. System.err.println("Scheduler termination interrupted.");
  54. }
  55. }
  56. public static void main(String[] args) {
  57. String[] variables = {"MY_API_KEY", "DATABASE_URL", "DEBUG"};
  58. long interval = 2000; // Retry every 2 seconds
  59. EnvVariableFilter filter = new EnvVariableFilter(variables, interval);
  60. filter.initialize();
  61. // Keep the program running for a while to allow retries
  62. try {
  63. Thread.sleep(10000);
  64. } catch (InterruptedException e) {
  65. e.printStackTrace();
  66. }
  67. filter.stop();
  68. Map<String, String> filteredVars = filter.getFilteredEnvVars();
  69. System.out.println(filteredVars);
  70. }
  71. }

Add your comment