1. import java.io.*;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. public class HeaderMetadataAttacher {
  5. /**
  6. * Attaches metadata from a configuration file to request headers.
  7. *
  8. * @param requestHeaders A map of request headers.
  9. * @param configFilePath The path to the configuration file.
  10. * @return The updated map of request headers.
  11. * @throws IOException If an error occurs while reading the configuration file.
  12. */
  13. public static Map<String, String> attachMetadata(Map<String, String> requestHeaders, String configFilePath) throws IOException {
  14. // Load configuration from file
  15. Map<String, String> metadata = loadMetadata(configFilePath);
  16. // Merge metadata into request headers
  17. if (metadata != null) {
  18. requestHeaders.putAll(metadata); // Add new or update existing headers
  19. }
  20. return requestHeaders;
  21. }
  22. /**
  23. * Loads metadata from a configuration file.
  24. *
  25. * @param filePath The path to the configuration file.
  26. * @return A map of metadata, or null if the file cannot be loaded.
  27. * @throws IOException If an error occurs while reading the file.
  28. */
  29. private static Map<String, String> loadMetadata(String filePath) throws IOException {
  30. Map<String, String> metadata = new HashMap<>();
  31. try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
  32. String line;
  33. while ((line = reader.readLine()) != null) {
  34. String[] parts = line.split(":", 2); // Split into key and value
  35. if (parts.length == 2) {
  36. String key = parts[0].trim();
  37. String value = parts[1].trim();
  38. metadata.put(key, value);
  39. }
  40. }
  41. } catch (IOException e) {
  42. System.err.println("Error loading metadata from file: " + e.getMessage());
  43. return null; // Return null if file loading fails
  44. }
  45. return metadata;
  46. }
  47. public static void main(String[] args) {
  48. // Example usage
  49. Map<String, String> requestHeaders = new HashMap<>();
  50. requestHeaders.put("Content-Type", "application/json");
  51. String configFilePath = "metadata.config"; // Replace with your config file path
  52. try {
  53. Map<String, String> updatedHeaders = attachMetadata(requestHeaders, configFilePath);
  54. System.out.println(updatedHeaders);
  55. } catch (IOException e) {
  56. System.err.println("Error: " + e.getMessage());
  57. }
  58. }
  59. }

Add your comment