tdudzik

Epoch time

Mar 28th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. public class EpochTimeValidator implements ConstraintValidator<EpochTime, Long> {
  2.  
  3. @Override
  4. public void initialize(EpochTime constraintAnnotation) {
  5. }
  6.  
  7. @Override
  8. public boolean isValid(Long time, ConstraintValidatorContext constraintValidatorContext) {
  9. long nowInEpochTime = LocalDateTime.now(ZoneOffset.UTC).toEpochSecond(ZoneOffset.ofHours(0));
  10. return time != null && time >= 0 && time <= nowInEpochTime;
  11. }
  12.  
  13. }
  14.  
  15. public class EpochTimeValidatorTest {
  16.  
  17. private final ConstraintValidator<EpochTime, Long> constraintValidator = new EpochTimeValidator();
  18.  
  19. @Test
  20. public void shouldBeValid() {
  21. // when
  22. long time = LocalDateTime.now(ZoneOffset.UTC).toEpochSecond(ZoneOffset.ofHours(0));
  23. boolean isValid = constraintValidator.isValid(time, null);
  24.  
  25. // then
  26. assertEquals(isValid, true);
  27. }
  28.  
  29. @Test
  30. public void shouldBeInvalidWhenTimeIsInTheFuture() {
  31. // when
  32. long time = LocalDateTime.now(ZoneOffset.UTC).plusSeconds(1).toEpochSecond(ZoneOffset.ofHours(0));
  33. boolean isValid = constraintValidator.isValid(time, null);
  34.  
  35. // then
  36. assertEquals(isValid, false);
  37. }
  38.  
  39. @Test
  40. public void shouldBeInvalidWhenTimeIsNegative() {
  41. // when
  42. long time = -100;
  43. boolean isValid = constraintValidator.isValid(time, null);
  44.  
  45. // then
  46. assertEquals(isValid, false);
  47. }
  48.  
  49. }
Advertisement
Add Comment
Please, Sign In to add comment