]> WPIA git - gigi.git/blob - src/org/cacert/gigi/util/Job.java
New Signer Job Table.
[gigi.git] / src / org / cacert / gigi / util / Job.java
1 package org.cacert.gigi.util;
2
3 import java.sql.PreparedStatement;
4 import java.sql.ResultSet;
5 import java.sql.SQLException;
6
7 import org.cacert.gigi.Certificate;
8 import org.cacert.gigi.database.DatabaseConnection;
9
10 public class Job {
11         int id;
12
13         private Job(int id) {
14                 this.id = id;
15         }
16
17         public static enum JobType {
18                 SIGN("sign"), REVOKE("revoke");
19                 private final String name;
20
21                 private JobType(String name) {
22                         this.name = name;
23                 }
24
25                 public String getName() {
26                         return name;
27                 }
28         }
29
30         public static Job submit(Certificate targetId, JobType type) throws SQLException {
31                 PreparedStatement ps = DatabaseConnection.getInstance().prepare("INSERT INTO `jobs` SET targetId=?, task=?");
32                 ps.setInt(1, targetId.getId());
33                 ps.setString(2, type.getName());
34                 ps.execute();
35                 return new Job(DatabaseConnection.lastInsertId(ps));
36         }
37
38         public boolean waitFor(int max) throws SQLException, InterruptedException {
39                 long start = System.currentTimeMillis();
40                 PreparedStatement ps = DatabaseConnection.getInstance().prepare(
41                         "SELECT 1 FROM `jobs` WHERE id=? AND state='open'");
42                 ps.setInt(1, id);
43                 ResultSet rs = ps.executeQuery();
44                 while (rs.next()) {
45                         rs.close();
46                         if (max != 0 && System.currentTimeMillis() - start > max) {
47                                 return false;
48                         }
49                         Thread.sleep((long) (2000 + Math.random() * 2000));
50                         rs = ps.executeQuery();
51                 }
52                 rs.close();
53                 return true;
54         }
55 }