1. import java.io.File;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. public class LogFileParameterInjector {
  5. private static final String DEFAULT_LOG_FILE = "default.log";
  6. private static final String DEVELOPMENT_LOG_FILE_PREFIX = "dev_";
  7. /**
  8. * Injects parameters from log files. Handles file not found gracefully.
  9. *
  10. * @param params A map of parameter names to default values.
  11. * @return A map of parameter names to the injected values. Returns the original params if any file is not found.
  12. */
  13. public static Map<String, String> injectParameters(Map<String, String> params) {
  14. Map<String, String> injectedParams = new HashMap<>(params); // Create a copy to avoid modifying the original
  15. for (Map.Entry<String, String> entry : params.entrySet()) {
  16. String paramName = entry.getKey();
  17. String defaultValue = entry.getValue();
  18. String logFileName = DEVELOPMENT_LOG_FILE_PREFIX + paramName + ".log";
  19. File logFile = new File(logFileName);
  20. try {
  21. String fileContent = FileUtils.readUtf8FileContent(logFile); // Assuming FileUtils.readUtf8FileContent is available or implement it
  22. if (fileContent != null && !fileContent.isEmpty()) {
  23. injectedParams.put(paramName, fileContent.trim());
  24. }
  25. } catch (Exception e) {
  26. // Log file not found or error reading. Keep the default value.
  27. System.err.println("Log file not found or error reading for " + logFileName + ". Using default value.");
  28. }
  29. }
  30. return injectedParams;
  31. }
  32. //Helper class for reading file content
  33. static class FileUtils {
  34. public static String readUtf8FileContent(File file) throws Exception {
  35. return java.nio.file.Files.readString(file.toPath(), java.nio.charset.StandardCharsets.UTF_8);
  36. }
  37. }
  38. }

Add your comment