| 1 | package com.hammurapi.extract; |
| 2 | |
| 3 | import java.util.Collections; |
| 4 | import java.util.Map; |
| 5 | import java.util.Set; |
| 6 | import java.util.concurrent.TimeUnit; |
| 7 | |
| 8 | /** |
| 9 | * This predicate evaluates to true for <code>timeInterval</code> after construction. |
| 10 | * Then it evaluates to false. |
| 11 | * @author Pavel Vlasov |
| 12 | * |
| 13 | * @param <T> |
| 14 | * @param <C> |
| 15 | */ |
| 16 | public class TimeIntervalPredicate<T,C> implements Predicate<T,C> { |
| 17 | |
| 18 | private boolean nanos; |
| 19 | long end; |
| 20 | |
| 21 | public TimeIntervalPredicate(TimeUnit timeUnit, long interval) { |
| 22 | nanos = TimeUnit.MILLISECONDS.compareTo(timeUnit)>0; |
| 23 | long start = nanos ? System.nanoTime() : System.currentTimeMillis(); |
| 24 | end = start + (nanos ? TimeUnit.NANOSECONDS : TimeUnit.MILLISECONDS).convert(interval, timeUnit); |
| 25 | } |
| 26 | |
| 27 | @Override |
| 28 | public Boolean extract( |
| 29 | C context, |
| 30 | Map<C, Map<Extractor<T, ? super Boolean, C>, ? super Boolean>> cache, |
| 31 | T... obj) { |
| 32 | return (nanos ? System.nanoTime() : System.currentTimeMillis()) < end; |
| 33 | } |
| 34 | |
| 35 | @Override |
| 36 | public Set<Integer> parameterIndices() { |
| 37 | return Collections.emptySet(); |
| 38 | } |
| 39 | |
| 40 | @Override |
| 41 | public boolean isContextDependent() { |
| 42 | return false; |
| 43 | } |
| 44 | |
| 45 | @Override |
| 46 | public ComparisonResult compareTo(Extractor<T, Boolean, C> other) { |
| 47 | if (equals(other)) { |
| 48 | return ComparisonResult.EQUAL_NM; |
| 49 | } |
| 50 | return ComparisonResult.NOT_EQUAL_NM; |
| 51 | } |
| 52 | |
| 53 | @Override |
| 54 | public double getCost() { |
| 55 | return 0; |
| 56 | } |
| 57 | |
| 58 | @Override |
| 59 | public int hashCode() { |
| 60 | final int prime = 31; |
| 61 | int result = 1; |
| 62 | result = prime * result + (int) (end ^ (end >>> 32)); |
| 63 | result = prime * result + (nanos ? 1231 : 1237); |
| 64 | return result; |
| 65 | } |
| 66 | |
| 67 | @Override |
| 68 | public boolean equals(Object obj) { |
| 69 | if (this == obj) |
| 70 | return true; |
| 71 | if (obj == null) |
| 72 | return false; |
| 73 | if (getClass() != obj.getClass()) |
| 74 | return false; |
| 75 | TimeIntervalPredicate other = (TimeIntervalPredicate) obj; |
| 76 | if (end != other.end) |
| 77 | return false; |
| 78 | if (nanos != other.nanos) |
| 79 | return false; |
| 80 | return true; |
| 81 | } |
| 82 | |
| 83 | } |