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