import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class HeaderMetadataAttacher {
/**
* Attaches metadata from a configuration file to request headers.
*
* @param requestHeaders A map of request headers.
* @param configFilePath The path to the configuration file.
* @return The updated map of request headers.
* @throws IOException If an error occurs while reading the configuration file.
*/
public static Map<String, String> attachMetadata(Map<String, String> requestHeaders, String configFilePath) throws IOException {
// Load configuration from file
Map<String, String> metadata = loadMetadata(configFilePath);
// Merge metadata into request headers
if (metadata != null) {
requestHeaders.putAll(metadata); // Add new or update existing headers
}
return requestHeaders;
}
/**
* Loads metadata from a configuration file.
*
* @param filePath The path to the configuration file.
* @return A map of metadata, or null if the file cannot be loaded.
* @throws IOException If an error occurs while reading the file.
*/
private static Map<String, String> loadMetadata(String filePath) throws IOException {
Map<String, String> metadata = new HashMap<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(":", 2); // Split into key and value
if (parts.length == 2) {
String key = parts[0].trim();
String value = parts[1].trim();
metadata.put(key, value);
}
}
} catch (IOException e) {
System.err.println("Error loading metadata from file: " + e.getMessage());
return null; // Return null if file loading fails
}
return metadata;
}
public static void main(String[] args) {
// Example usage
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("Content-Type", "application/json");
String configFilePath = "metadata.config"; // Replace with your config file path
try {
Map<String, String> updatedHeaders = attachMetadata(requestHeaders, configFilePath);
System.out.println(updatedHeaders);
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Add your comment