There is a remote resource containing datasets arranged by time, data is static and doesnt change. Whenever we are going to fetch anything from there we will be saving it in our cache. User might request a data for a particular time period, lets say from 1st Jan 2019 to 1st Jan 2020. If data is not cached, then we request it from remote resource, in case only part of data is cached, then we need to request what is missing. There is a function which calculates missing intervals, and I think that it looks too verbose. Would be nice to get some suggestions for a better solution. Thanks.
@SneakyThrows
public static ArrayList<TimeSpan> difference(TimeSpan requested, TimeSpan cached){
ArrayList<TimeSpan> missingIntervals = new ArrayList<>();
//requested period is within cached
if (requested.getFrom().compareTo(cached.getFrom()) >= 0 && requested.getTo().compareTo(cached.getTo()) <= 0){
missingIntervals = null;
//requested period is before or after cached
} else if (requested.getTo().compareTo(cached.getFrom()) <= 0 || requested.getFrom().compareTo(cached.getTo()) >= 0){
missingIntervals.add(requested);
// requested start and end dates are outside of cached range
} else if (requested.getFrom().compareTo(cached.getFrom()) <= 0 && requested.getTo().compareTo(cached.getTo()) >= 0){
missingIntervals.add(new TimeSpan(requested.getFrom(),cached.getFrom()));
missingIntervals.add(new TimeSpan(cached.getTo(),requested.getTo()));
// requested start date is before cached period
} else if (requested.getFrom().compareTo(cached.getFrom()) < 0
&& requested.getTo().compareTo(cached.getTo()) <= 0
&& requested.getTo().compareTo(cached.getFrom()) > 0){
missingIntervals.add(new TimeSpan(requested.getFrom(),cached.getFrom()));
// requested end date is after cached period
} else if (requested.getTo().compareTo(cached.getTo()) >= 0
&& requested.getFrom().compareTo(cached.getFrom()) >= 0
&& requested.getFrom().compareTo(cached.getTo()) < 0){
missingIntervals.add(new TimeSpan(cached.getTo(),requested.getTo()));
}
return missingIntervals;
}
Here is a TimeSpan class:
public class TimeSpan {
public TimeSpan(Date from, Date to) throws Exception{
if(from.compareTo(to) >= 0){
throw new Exception("Start date cannot be greater then end date");
}
this.from = from;
this.to = to;
}
private final Date from;
private final Date to;
}