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