1 package org.cacert.gigi.dbObjects;
3 import java.util.Arrays;
5 import java.util.HashMap;
8 import org.cacert.gigi.Gigi;
9 import org.cacert.gigi.GigiApiException;
10 import org.cacert.gigi.database.GigiPreparedStatement;
11 import org.cacert.gigi.database.GigiResultSet;
12 import org.cacert.gigi.output.template.Scope;
13 import org.cacert.gigi.output.template.SprintfCommand;
15 public class DomainPingConfiguration implements IdCachable {
17 private static final int REPING_MINIMUM_DELAY = 5 * 60 * 1000;
21 private Domain target;
23 private DomainPingType type;
27 private DomainPingConfiguration(int id) {
28 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `id`, `domainid`, `type`, `info` FROM `pingconfig` WHERE `id`=?")) {
31 GigiResultSet rs = ps.executeQuery();
33 throw new IllegalArgumentException("Invalid pingconfig id " + id);
35 this.id = rs.getInt("id");
36 target = Domain.getById(rs.getInt("domainid"));
37 type = DomainPingType.valueOf(rs.getString("type").toUpperCase());
38 info = rs.getString("info");
47 public Domain getTarget() {
51 public DomainPingType getType() {
55 public String getInfo() {
59 private static ObjectCache<DomainPingConfiguration> cache = new ObjectCache<>();
61 public static synchronized DomainPingConfiguration getById(int id) {
62 DomainPingConfiguration res = cache.get(id);
64 cache.put(res = new DomainPingConfiguration(id));
69 public Date getLastExecution() {
70 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `when` AS stamp from `domainPinglog` WHERE `configId`=? ORDER BY `when` DESC LIMIT 1")) {
72 GigiResultSet rs = ps.executeQuery();
74 return new Date(rs.getTimestamp("stamp").getTime());
80 public Date getLastSuccess() {
81 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT `when` AS stamp from `domainPinglog` WHERE `configId`=? AND state='success' ORDER BY `when` DESC LIMIT 1")) {
83 GigiResultSet rs = ps.executeQuery();
85 return new Date(rs.getTimestamp("stamp").getTime());
91 public synchronized void requestReping() throws GigiApiException {
92 Date lastExecution = getLastExecution();
93 if (lastExecution.getTime() + REPING_MINIMUM_DELAY < System.currentTimeMillis()) {
94 Gigi.notifyPinger(this);
97 Map<String, Object> data = new HashMap<String, Object>();
98 data.put("delay", REPING_MINIMUM_DELAY / 60 / 1000);
99 data.put("data", new Date(lastExecution.getTime() + REPING_MINIMUM_DELAY));
100 throw new GigiApiException(new Scope(new SprintfCommand("Reping is only allowed after {0} minutes, yours end at {1}.", Arrays.asList("${delay}", "${data}")), data));