1. import java.time.LocalDateTime;
  2. import java.time.format.DateTimeFormatter;
  3. import java.util.function.Consumer;
  4. class TimeValidator {
  5. /**
  6. * Wraps a function that validates a time value, handling potential errors with limited memory.
  7. *
  8. * @param validator A function that takes a LocalDateTime and returns true if valid, false otherwise.
  9. * @param errorMessage The error message to be associated with validation failures.
  10. * @return A validation wrapper that can be used to execute the validation function.
  11. */
  12. public static ValidationWrapper<LocalDateTime> wrapValidation(Consumer<LocalDateTime> validator, String errorMessage) {
  13. return new ValidationWrapper<>(validator, errorMessage);
  14. }
  15. /**
  16. * Represents a wrapped validation result, including the validation function and error message.
  17. */
  18. static class ValidationWrapper<T> {
  19. private final Consumer<T> validator;
  20. private final String errorMessage;
  21. ValidationWrapper(Consumer<T> validator, String errorMessage) {
  22. this.validator = validator;
  23. this.errorMessage = errorMessage;
  24. }
  25. /**
  26. * Executes the validation function and handles any errors.
  27. *
  28. * @param time The time value to be validated.
  29. * @throws IllegalArgumentException if the validation function fails.
  30. */
  31. public void validate(LocalDateTime time) {
  32. try {
  33. validator.accept(time);
  34. } catch (Exception e) {
  35. throw new IllegalArgumentException(errorMessage + ": " + e.getMessage(), e); // Re-throw with context
  36. }
  37. }
  38. }
  39. public static void main(String[] args) {
  40. // Example usage
  41. ValidationWrapper<LocalDateTime> validator = TimeValidator.wrapValidation(time -> {
  42. if (time.isBefore(LocalDateTime.now())) {
  43. throw new IllegalArgumentException("Time cannot be in the past.");
  44. }
  45. // Add other validation rules here
  46. }, "Invalid time value");
  47. try {
  48. validator.validate(LocalDateTime.now().plusDays(1)); //Valid
  49. System.out.println("Validation successful");
  50. validator.validate(LocalDateTime.now().minusDays(1)); // Invalid - should throw exception
  51. } catch (IllegalArgumentException e) {
  52. System.err.println("Validation failed: " + e.getMessage());
  53. }
  54. }
  55. }

Add your comment