84c012c3586a55d564e43d747dd7a61528ce6c26
[gigi.git] / util / org / cacert / gigi / util / DatabaseManager.java
1 package org.cacert.gigi.util;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.InputStreamReader;
8 import java.io.Reader;
9 import java.sql.Connection;
10 import java.sql.DriverManager;
11 import java.sql.SQLException;
12 import java.sql.Statement;
13 import java.util.Properties;
14
15 import org.cacert.gigi.database.DatabaseConnection;
16 import org.cacert.gigi.database.SQLFileManager;
17 import org.cacert.gigi.database.SQLFileManager.ImportType;
18
19 public class DatabaseManager {
20
21     public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {
22         boolean test = false;
23         if (args.length >= 1 && args[0].equals("--test")) {
24             test = true;
25             String[] ne = new String[args.length - 1];
26             System.arraycopy(args, 1, ne, 0, ne.length);
27             args = ne;
28         }
29         if (args.length == 0) {
30             Properties p = new Properties();
31             try (Reader reader = new InputStreamReader(new FileInputStream("config/gigi.properties"), "UTF-8")) {
32                 p.load(reader);
33             }
34             args = new String[] {
35                     p.getProperty("sql.driver"), p.getProperty("sql.url"), p.getProperty("sql.user"), p.getProperty("sql.password")
36             };
37         }
38         if (args.length < 4) {
39             System.err.println("Usage: com.mysql.jdbc.Driver jdbc:mysql://localhost/cacert user password");
40             return;
41         }
42         run(args, test ? ImportType.TEST : ImportType.PRODUCTION);
43     }
44
45     public static void run(String[] args, ImportType truncate) throws ClassNotFoundException, SQLException, IOException {
46         Class.forName(args[0]);
47         Connection conn = DriverManager.getConnection(args[1], args[2], args[3]);
48         conn.setAutoCommit(false);
49         Statement stmt = conn.createStatement();
50         try (InputStream structure = DatabaseConnection.class.getResourceAsStream("tableStructure.sql")) {
51             SQLFileManager.addFile(stmt, structure, truncate);
52         }
53         File localData = new File("doc/sampleData.sql");
54         if (localData.exists()) {
55             try (FileInputStream f = new FileInputStream(localData)) {
56                 SQLFileManager.addFile(stmt, f, ImportType.PRODUCTION);
57             }
58         }
59         stmt.executeBatch();
60         conn.commit();
61         stmt.close();
62
63         conn.close();
64     }
65
66 }