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 {
20 public static enum JobType implements DBEnum {
21 SIGN("sign"), REVOKE("revoke");
23 private final String name;
25 private JobType(String name) {
30 public String getDBName() {
35 protected synchronized static Job sign(Certificate targetId, Date start, String period) throws GigiApiException {
36 CertificateValiditySelector.checkValidityLength(period);
37 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `jobs` SET targetId=?, task=?::`jobType`, executeFrom=?, executeTo=?")) {
38 ps.setInt(1, targetId.getId());
39 ps.setEnum(2, JobType.SIGN);
41 ps.setString(4, period);
43 return cache.put(new Job(ps.lastInsertId()));
47 protected synchronized static Job revoke(Certificate targetId, RevocationType type) {
48 return revoke(targetId, type, null, null, null);
51 protected synchronized static Job revoke(Certificate targetId, String challenge, String signature, String message) {
52 return revoke(targetId, RevocationType.KEY_COMPROMISE, challenge, signature, message);
55 private synchronized static Job revoke(Certificate targetId, RevocationType type, String challenge, String signature, String message) {
56 try (GigiPreparedStatement ps = new GigiPreparedStatement("UPDATE `certs` SET `revocationType`=?::`revocationType`, `revocationChallenge`=?, `revocationSignature`=?, `revocationMessage`=? WHERE id=?")) {
58 ps.setString(2, challenge);
59 ps.setString(3, signature);
60 ps.setString(4, message);
61 ps.setInt(5, targetId.getId());
65 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `jobs` SET targetId=?, task=?::`jobType`")) {
66 ps.setInt(1, targetId.getId());
67 ps.setEnum(2, JobType.REVOKE);
69 return cache.put(new Job(ps.lastInsertId()));
73 public synchronized boolean waitFor(int max) {
74 long start = System.currentTimeMillis();
75 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT 1 FROM `jobs` WHERE id=? AND state='open'")) {
77 GigiResultSet rs = ps.executeQuery();
80 if (max != 0 && System.currentTimeMillis() - start > max) {
84 this.wait((long) (2000 + Math.random() * 2000));
85 } catch (InterruptedException ie) {
86 // Ignore the interruption
89 rs = ps.executeQuery();
100 static ObjectCache<Job> cache = new ObjectCache<>();
102 public synchronized static Job getById(int id) {
103 Job i = cache.get(id);
107 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT 1 FROM `jobs` WHERE id=?")) {
109 GigiResultSet rs = ps.executeQuery();