net.intelie.pipes.time.CronPeriod Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of pipes-api Show documentation
Show all versions of pipes-api Show documentation
Intelie Pipes' API classes and interfaces
package net.intelie.pipes.time;
import net.intelie.pipes.cron.Cron;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class CronPeriod implements Period {
private static final long serialVersionUID = 1L;
private final Cron cron;
private final String expression;
private final ZoneId zone;
public CronPeriod(String expression) {
this(expression, null);
}
public CronPeriod(String expression, ZoneId zone) {
this(new Cron(expression), expression, zone);
}
private CronPeriod(Cron cron, String expression, ZoneId zone) {
this.cron = cron;
this.expression = expression;
this.zone = zone == null ? ZoneId.systemDefault() : zone;
}
@Override
public Map simple() {
Map map = new HashMap<>();
map.put("amount", expression);
map.put("unit", "cron");
map.put("zone", zone.getId());
return map;
}
@Override
public CronPeriod forceZone(ZoneId zone) {
return new CronPeriod(cron, expression, zone);
}
@Override
public String toString(boolean includeOne) {
return "cron('" + expression + "')";
}
@Override
public String toString() {
return toString(true);
}
@Override
public long add(long timestamp) {
return toLong(cron.next(toDate(timestamp)));
}
@Override
public long sub(long timestamp) {
return toLong(cron.prev(toDate(timestamp)));
}
@Override
public long floor(long timestamp) {
return toLong(cron.prevOrSame(toDate(timestamp)));
}
private long toLong(ZonedDateTime date) {
if (date == null) return Long.MAX_VALUE;
return date.toInstant().toEpochMilli();
}
private ZonedDateTime toDate(long timestamp) {
return ZonedDateTime.ofInstant(Instant.ofEpochMilli(timestamp), zone);
}
@Override
public boolean supportsFloor() {
return true;
}
@Override
public long estimateMillis() {
return add(1400000000000L) - floor(1400000000000L);
}
@Override
public Period multiply(int amount) {
if (amount == 1)
return this;
return new MultiplyPeriod(amount, this);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CronPeriod)) return false;
CronPeriod that = (CronPeriod) o;
return Objects.equals(this.cron, that.cron) &&
Objects.equals(this.zone, that.zone);
}
@Override
public int hashCode() {
return Objects.hash(this.cron, this.zone);
}
}