]> WPIA git - gigi.git/blob - src/org/cacert/gigi/util/Job.java
[DB]: Add orgAdmin management code
[gigi.git] / src / org / cacert / gigi / util / Job.java
1 package org.cacert.gigi.util;
2
3 import java.sql.Date;
4
5 import org.cacert.gigi.GigiApiException;
6 import org.cacert.gigi.database.DatabaseConnection;
7 import org.cacert.gigi.database.GigiPreparedStatement;
8 import org.cacert.gigi.database.GigiResultSet;
9 import org.cacert.gigi.dbObjects.Certificate;
10 import org.cacert.gigi.output.CertificateValiditySelector;
11
12 public class Job {
13
14     private int id;
15
16     private Job(int id) {
17         this.id = id;
18     }
19
20     public static enum JobType {
21         SIGN("sign"), REVOKE("revoke");
22
23         private final String name;
24
25         private JobType(String name) {
26             this.name = name;
27         }
28
29         public String getName() {
30             return name;
31         }
32     }
33
34     public static Job sign(Certificate targetId, Date start, String period) throws GigiApiException {
35         CertificateValiditySelector.checkValidityLength(period);
36         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `jobs` SET targetId=?, task=?, executeFrom=?, executeTo=?");
37         ps.setInt(1, targetId.getId());
38         ps.setString(2, JobType.SIGN.getName());
39         ps.setDate(3, start);
40         ps.setString(4, period);
41         ps.execute();
42         return new Job(ps.lastInsertId());
43     }
44
45     public static Job revoke(Certificate targetId) {
46
47         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `jobs` SET targetId=?, task=?");
48         ps.setInt(1, targetId.getId());
49         ps.setString(2, JobType.REVOKE.getName());
50         ps.execute();
51         return new Job(ps.lastInsertId());
52     }
53
54     public boolean waitFor(int max) throws InterruptedException {
55         long start = System.currentTimeMillis();
56         GigiPreparedStatement ps = DatabaseConnection.getInstance().prepare("SELECT 1 FROM `jobs` WHERE id=? AND state='open'");
57         ps.setInt(1, id);
58         GigiResultSet rs = ps.executeQuery();
59         while (rs.next()) {
60             rs.close();
61             if (max != 0 && System.currentTimeMillis() - start > max) {
62                 return false;
63             }
64             Thread.sleep((long) (2000 + Math.random() * 2000));
65             rs = ps.executeQuery();
66         }
67         rs.close();
68         return true;
69     }
70 }