import java.util.HashMap;
import java.util.Map;
public class EnvironmentVariableValidator {
/**
* Validates environment variables for data migration.
*
* @param expectedVariables A map of expected environment variable names to their expected values.
* @return A map of variable names that are missing or have invalid values. Returns an empty map if all variables are valid.
*/
public static Map<String, String> validateEnvironmentVariables(Map<String, String> expectedVariables) {
Map<String, String> validationErrors = new HashMap<>();
if (expectedVariables == null || expectedVariables.isEmpty()) {
return validationErrors; // Return empty map if no variables to validate
}
for (Map.Entry<String, String> entry : expectedVariables.entrySet()) {
String variableName = entry.getKey();
String expectedValue = entry.getValue();
String actualValue = System.getenv(variableName);
if (actualValue == null) {
validationErrors.put(variableName, "Missing environment variable");
} else if (!actualValue.equals(expectedValue)) {
validationErrors.put(variableName, "Incorrect value. Expected: " + expectedValue + ", Actual: " + actualValue);
}
//Handle empty string as a potential valid value if defined in the requirements.
else if (actualValue.trim().isEmpty() && expectedValue.trim().isEmpty()) {
continue; // Skip if both are empty
}
else if (actualValue.trim().isEmpty() && !expectedValue.trim().isEmpty()) {
validationErrors.put(variableName, "Missing environment variable");
}
}
return validationErrors;
}
public static void main(String[] args) {
//Example Usage
Map<String, String> expectedVars = new HashMap<>();
expectedVars.put("DATABASE_URL", "jdbc:mysql://localhost:3306/mydatabase");
expectedVars.put("API_KEY", "abcdef123456");
expectedVars.put("DEBUG_MODE", "true");
Map<String, String> errors = validateEnvironmentVariables(expectedVars);
if (errors.isEmpty()) {
System.out.println("All environment variables are valid.");
} else {
System.out.println("Validation errors:");
for (Map.Entry<String, String> error : errors.entrySet()) {
System.out.println(error.getKey() + ": " + error.getValue());
}
}
//Edge case: Empty expected variables
Map<String, String> emptyExpected = new HashMap<>();
Map<String, String> emptyResult = validateEnvironmentVariables(emptyExpected);
System.out.println("Empty Expected Result size: " + emptyResult.size()); //Expect 0
//Edge case: null expected variables
Map<String, String> nullExpected = null;
Map<String, String> nullResult = validateEnvironmentVariables(nullExpected);
System.out.println("Null Expected Result size: " + nullResult.size()); //Expect 0
//Edge case: Empty String
Map<String, String> emptyStringExpected = new HashMap<>();
emptyStringExpected.put("EMPTY_VAR", "");
Map<String, String> emptyStringResult = validateEnvironmentVariables(emptyStringExpected);
System.out.println("Empty String Result size: " + emptyStringResult.size()); //Expect 0
}
}
Add your comment