1. import java.time.LocalDate;
  2. import java.time.format.DateTimeFormatter;
  3. import java.util.Map;
  4. public class DryRunDateBootstrapper {
  5. /**
  6. * Bootsmaps scripts with date values for dry-run scenarios, supporting older Java versions.
  7. *
  8. * @param scripts A map where keys are script names and values are script content strings.
  9. * @param dateValues A map where keys are script names and values are date strings (e.g., "YYYY-MM-DD").
  10. * @param formatter The DateTimeFormatter to use for parsing date strings.
  11. * @return A map of script names to their bootstrapped content.
  12. */
  13. public static Map<String, String> bootstrapScripts(Map<String, String> scripts, Map<String, String> dateValues, DateTimeFormatter formatter) {
  14. Map<String, String> bootstrappedScripts = new java.util.HashMap<>();
  15. for (Map.Entry<String, String> entry : scripts.entrySet()) {
  16. String scriptName = entry.getKey();
  17. String scriptContent = entry.getValue();
  18. String dateString = dateValues.get(scriptName);
  19. if (dateString != null) {
  20. try {
  21. LocalDate date = LocalDate.parse(dateString, formatter);
  22. // Replace date placeholders in the script content. Example: "System.out.println(date);"
  23. scriptContent = scriptContent.replace("{{date}}", date.toString());
  24. } catch (Exception e) {
  25. System.err.println("Error parsing date for script " + scriptName + ": " + dateString + ". Using original script.");
  26. // Handle the error gracefully, e.g., log it or use a default date.
  27. }
  28. }
  29. bootstrappedScripts.put(scriptName, scriptContent);
  30. }
  31. return bootstrappedScripts;
  32. }
  33. public static void main(String[] args) {
  34. //Example Usage
  35. Map<String, String> scripts = new java.util.HashMap<>();
  36. scripts.put("script1", "System.out.println(Today's date: {{date}})");
  37. scripts.put("script2", "System.out.println(\"Script 2 run on:\", {{date}})");
  38. Map<String, String> dateValues = new java.util.HashMap<>();
  39. dateValues.put("script1", "2024-01-15");
  40. dateValues.put("script2", "2024-02-28");
  41. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
  42. Map<String, String> bootstrapped = bootstrapScripts(scripts, dateValues, formatter);
  43. for(Map.Entry<String, String> entry : bootstrapped.entrySet()) {
  44. System.out.println(entry.getKey() + ": " + entry.getValue());
  45. }
  46. }
  47. }

Add your comment