TimeFrameValidator.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package net.bananasplayground.validator;
  2. import java.time.LocalDateTime;
  3. import java.time.format.DateTimeFormatter;
  4. import org.apache.commons.lang3.StringUtils;
  5. import com.vaadin.data.ValidationResult;
  6. import com.vaadin.data.ValueContext;
  7. import com.vaadin.data.validator.AbstractValidator;
  8. /**
  9. * Klimbim Software collection, A bag full of things
  10. * Copyright (C) 2011-2023 Johannes 'Banana' Keßler
  11. *
  12. * This program is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation, either version 3 of the License, or
  15. * (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License
  23. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  24. */
  25. /**
  26. * @see net.bananasplayground.validator.TimeFrameValidatorDefinition
  27. */
  28. public class TimeFrameValidator extends AbstractValidator<LocalDateTime> {
  29. private final String errorMessage;
  30. private final TimeFrameValidatorDefinition definition;
  31. protected TimeFrameValidator(String errorMessage, TimeFrameValidatorDefinition definition) {
  32. super(errorMessage);
  33. this.errorMessage = errorMessage;
  34. this.definition = definition;
  35. }
  36. @Override
  37. public ValidationResult apply(LocalDateTime value, ValueContext context) {
  38. if(StringUtils.isAnyBlank(definition.getTimeTo(), definition.getTimeFrom())) return ValidationResult.ok();
  39. boolean isValid = false;
  40. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
  41. LocalDateTime timeFrom = LocalDateTime.parse(value.format(formatter) +"T"+definition.getTimeFrom());
  42. LocalDateTime timeTo = LocalDateTime.parse(value.format(formatter) +"T"+definition.getTimeTo());
  43. if((value.isEqual(timeFrom) || value.isAfter(timeFrom)) && (value.isEqual(timeTo) || value.isBefore(timeTo))) {
  44. isValid = true;
  45. }
  46. return isValid ? ValidationResult.ok() : ValidationResult.error(this.errorMessage);
  47. }
  48. }