import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class ResponseHeaderValidator {
/**
* Validates response headers against a configuration file.
* @param responseHeaders A map of response headers.
* @param configFilePath The path to the configuration file.
* @return true if all headers are valid, false otherwise.
*/
public static boolean validateHeaders(Map<String, String> responseHeaders, String configFilePath) {
try {
// Read the configuration file.
File configFile = new File(configFilePath);
Scanner scanner = new Scanner(configFile);
// Parse the configuration file.
Map<String, Map<String, String>> config = parseConfig(scanner);
scanner.close();
// Validate each header against the configuration.
for (Map.Entry<String, String> entry : responseHeaders.entrySet()) {
String headerName = entry.getKey();
String headerValue = entry.getValue();
if (config.containsKey(headerName)) {
String expectedValue = config.get(headerName).get("value");
if (!headerValue.equals(expectedValue)) {
System.out.println("Header " + headerName + " is invalid. Expected: " + expectedValue + ", Actual: " + headerValue);
return false; // Header validation failed.
}
} else {
System.out.println("Header " + headerName + " is missing in configuration.");
return false; // Header not found in config.
}
}
return true; // All headers are valid.
} catch (Exception e) {
System.err.println("Error validating headers: " + e.getMessage());
return false; // Error during validation.
}
}
/**
* Parses the configuration file.
* @param scanner The scanner for reading the configuration file.
* @return A map representing the configuration.
*/
private static Map<String, Map<String, String>> parseConfig(Scanner scanner) throws Exception {
Map<String, Map<String, String>> config = new HashMap<>();
String line;
while ((line = scanner.nextLine()) != null) {
String[] parts = line.split(":", 2); // Split into header and value.
if (parts.length == 2) {
String headerName = parts[0].trim();
String value = parts[1].trim();
config.put(headerName, new HashMap<>());
config.get(headerName).put("value", value);
}
}
return config;
}
public static void main(String[] args) {
//Example Usage
Map<String, String> responseHeaders = new HashMap<>();
responseHeaders.put("Content-Type", "application/json");
responseHeaders.put("X-Custom-Header", "example_value");
String configFilePath = "config.txt"; // Replace with your config file path
boolean isValid = validateHeaders(responseHeaders, configFilePath);
if (isValid) {
System.out.println("Response headers are valid.");
} else {
System.out.println("Response headers are invalid.");
}
}
}
Add your comment