import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Map;
public class DryRunDateBootstrapper {
/**
* Bootsmaps scripts with date values for dry-run scenarios, supporting older Java versions.
*
* @param scripts A map where keys are script names and values are script content strings.
* @param dateValues A map where keys are script names and values are date strings (e.g., "YYYY-MM-DD").
* @param formatter The DateTimeFormatter to use for parsing date strings.
* @return A map of script names to their bootstrapped content.
*/
public static Map<String, String> bootstrapScripts(Map<String, String> scripts, Map<String, String> dateValues, DateTimeFormatter formatter) {
Map<String, String> bootstrappedScripts = new java.util.HashMap<>();
for (Map.Entry<String, String> entry : scripts.entrySet()) {
String scriptName = entry.getKey();
String scriptContent = entry.getValue();
String dateString = dateValues.get(scriptName);
if (dateString != null) {
try {
LocalDate date = LocalDate.parse(dateString, formatter);
// Replace date placeholders in the script content. Example: "System.out.println(date);"
scriptContent = scriptContent.replace("{{date}}", date.toString());
} catch (Exception e) {
System.err.println("Error parsing date for script " + scriptName + ": " + dateString + ". Using original script.");
// Handle the error gracefully, e.g., log it or use a default date.
}
}
bootstrappedScripts.put(scriptName, scriptContent);
}
return bootstrappedScripts;
}
public static void main(String[] args) {
//Example Usage
Map<String, String> scripts = new java.util.HashMap<>();
scripts.put("script1", "System.out.println(Today's date: {{date}})");
scripts.put("script2", "System.out.println(\"Script 2 run on:\", {{date}})");
Map<String, String> dateValues = new java.util.HashMap<>();
dateValues.put("script1", "2024-01-15");
dateValues.put("script2", "2024-02-28");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
Map<String, String> bootstrapped = bootstrapScripts(scripts, dateValues, formatter);
for(Map.Entry<String, String> entry : bootstrapped.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Add your comment