import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class EnvVariableFilter {
private final Map<String, String> filteredEnvVars = new HashMap<>();
private final String[] variablesToFilter;
private final long retryIntervalMillis;
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public EnvVariableFilter(String[] variablesToFilter, long retryIntervalMillis) {
this.variablesToFilter = variablesToFilter;
this.retryIntervalMillis = retryIntervalMillis;
}
public void initialize() {
for (String var : variablesToFilter) {
try {
String value = System.getenv(var);
if (value != null && !value.isEmpty()) {
filteredEnvVars.put(var, value);
}
} catch (NullPointerException e) {
// Handle potential null pointer exceptions
System.err.println("Variable " + var + " not found.");
}
}
startRetryScheduler();
}
private void startRetryScheduler() {
for (String var : variablesToFilter) {
scheduler.scheduleAtFixedRate(() -> {
try {
String value = System.getenv(var);
if (value != null && !value.isEmpty()) {
filteredEnvVars.put(var, value);
} else {
System.err.println("Variable " + var + " not found (retry).");
}
} catch (NullPointerException e) {
System.err.println("Variable " + var + " not found (retry).");
}
}, retryIntervalMillis, retryIntervalMillis, TimeUnit.MILLISECONDS);
}
}
public Map<String, String> getFilteredEnvVars() {
return new HashMap<>(filteredEnvVars); // Return a copy to prevent external modification
}
public void stop() {
scheduler.shutdown();
try {
scheduler.awaitTermination(5, TimeUnit.SECONDS); // Give tasks time to finish
} catch (InterruptedException e) {
System.err.println("Scheduler termination interrupted.");
}
}
public static void main(String[] args) {
String[] variables = {"MY_API_KEY", "DATABASE_URL", "DEBUG"};
long interval = 2000; // Retry every 2 seconds
EnvVariableFilter filter = new EnvVariableFilter(variables, interval);
filter.initialize();
// Keep the program running for a while to allow retries
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
filter.stop();
Map<String, String> filteredVars = filter.getFilteredEnvVars();
System.out.println(filteredVars);
}
}
Add your comment