1 package club.wpia.gigi.dbObjects;
5 import club.wpia.gigi.GigiApiException;
6 import club.wpia.gigi.database.DBEnum;
7 import club.wpia.gigi.database.GigiPreparedStatement;
8 import club.wpia.gigi.database.GigiResultSet;
9 import club.wpia.gigi.dbObjects.Certificate.RevocationType;
10 import club.wpia.gigi.output.CertificateValiditySelector;
12 public class Job implements IdCachable {
14 public static int WAIT_MIN = 60000;
22 public static enum JobType implements DBEnum {
23 SIGN("sign"), REVOKE("revoke");
25 private final String name;
27 private JobType(String name) {
32 public String getDBName() {
37 protected synchronized static Job sign(Certificate targetId, Date start, String period) throws GigiApiException {
38 CertificateValiditySelector.checkValidityLength(period);
39 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `jobs` SET targetId=?, task=?::`jobType`, executeFrom=?, executeTo=?")) {
40 ps.setInt(1, targetId.getId());
41 ps.setEnum(2, JobType.SIGN);
43 ps.setString(4, period);
45 return cache.put(new Job(ps.lastInsertId()));
49 protected synchronized static Job revoke(Certificate targetId, RevocationType type) {
50 return revoke(targetId, type, null, null, null);
53 protected synchronized static Job revoke(Certificate targetId, String challenge, String signature, String message) {
54 return revoke(targetId, RevocationType.KEY_COMPROMISE, challenge, signature, message);
57 private synchronized static Job revoke(Certificate targetId, RevocationType type, String challenge, String signature, String message) {
58 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `certs` SET `revocationType`=?::`revocationType`, `revocationChallenge`=?, `revocationSignature`=?, `revocationMessage`=? WHERE id=?")) {
60 ps.setString(2, challenge);
61 ps.setString(3, signature);
62 ps.setString(4, message);
63 ps.setInt(5, targetId.getId());
67 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `jobs` SET targetId=?, task=?::`jobType`")) {
68 ps.setInt(1, targetId.getId());
69 ps.setEnum(2, JobType.REVOKE);
71 return cache.put(new Job(ps.lastInsertId()));
75 public synchronized boolean waitFor(int max) {
76 long start = System.currentTimeMillis();
77 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT 1 FROM `jobs` WHERE id=? AND state='open'")) {
79 GigiResultSet rs = ps.executeQuery();
82 if (max != 0 && System.currentTimeMillis() - start > max) {
86 this.wait((long) (2000 + Math.random() * 2000));
87 } catch (InterruptedException ie) {
88 // Ignore the interruption
91 rs = ps.executeQuery();
102 static ObjectCache<Job> cache = new ObjectCache<>();
104 public synchronized static Job getById(int id) {
105 Job i = cache.get(id);
109 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT 1 FROM `jobs` WHERE id=?")) {
111 GigiResultSet rs = ps.executeQuery();