1 package org.cacert.gigi.dbObjects;
5 import org.cacert.gigi.GigiApiException;
6 import org.cacert.gigi.database.GigiPreparedStatement;
7 import org.cacert.gigi.database.GigiResultSet;
8 import org.cacert.gigi.output.CertificateValiditySelector;
10 public class Job implements IdCachable {
18 public static enum JobType {
19 SIGN("sign"), REVOKE("revoke");
21 private final String name;
23 private JobType(String name) {
27 public String getName() {
32 public synchronized static Job sign(Certificate targetId, Date start, String period) throws GigiApiException {
33 CertificateValiditySelector.checkValidityLength(period);
34 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `jobs` SET targetId=?, task=?::`jobType`, executeFrom=?, executeTo=?")) {
35 ps.setInt(1, targetId.getId());
36 ps.setString(2, JobType.SIGN.getName());
38 ps.setString(4, period);
40 return cache.put(new Job(ps.lastInsertId()));
44 public synchronized static Job revoke(Certificate targetId) {
46 try (GigiPreparedStatement ps = new GigiPreparedStatement("INSERT INTO `jobs` SET targetId=?, task=?::`jobType`")) {
47 ps.setInt(1, targetId.getId());
48 ps.setString(2, JobType.REVOKE.getName());
50 return cache.put(new Job(ps.lastInsertId()));
54 public synchronized boolean waitFor(int max) {
55 long start = System.currentTimeMillis();
56 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT 1 FROM `jobs` WHERE id=? AND state='open'")) {
58 GigiResultSet rs = ps.executeQuery();
61 if (max != 0 && System.currentTimeMillis() - start > max) {
65 this.wait((long) (2000 + Math.random() * 2000));
66 } catch (InterruptedException ie) {
67 // Ignore the interruption
70 rs = ps.executeQuery();
81 static ObjectCache<Job> cache = new ObjectCache<>();
83 public synchronized static Job getById(int id) {
84 Job i = cache.get(id);
88 try (GigiPreparedStatement ps = new GigiPreparedStatement("SELECT 1 FROM `jobs` WHERE id=?'")) {
90 GigiResultSet rs = ps.executeQuery();