]> WPIA git - gigi.git/blob - util/org/cacert/gigi/util/DatabaseManager.java
9fe3f5fb3ec774416152fe2a5433193b667350a6
[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.FileReader;
5 import java.io.IOException;
6 import java.nio.file.Files;
7 import java.sql.Connection;
8 import java.sql.DriverManager;
9 import java.sql.SQLException;
10 import java.sql.Statement;
11 import java.util.Properties;
12
13 public class DatabaseManager {
14
15     public static String readFile(File f) throws IOException {
16         return new String(Files.readAllBytes(f.toPath()));
17     }
18
19     public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {
20         if (args.length == 0) {
21             Properties p = new Properties();
22             p.load(new FileReader("config/gigi.properties"));
23             args = new String[] {
24                     p.getProperty("sql.driver"), p.getProperty("sql.url"), p.getProperty("sql.user"), p.getProperty("sql.password")
25             };
26         }
27         if (args.length < 4) {
28             System.err.println("Usage: com.mysql.jdbc.Driver jdbc:mysql://localhost/cacert user password");
29             return;
30         }
31         run(args);
32     }
33
34     public static void run(String[] args) throws ClassNotFoundException, SQLException, IOException {
35         Class.forName(args[0]);
36         Connection conn = DriverManager.getConnection(args[1], args[2], args[3]);
37         Statement stmt = conn.createStatement();
38         addFile(stmt, new File("doc/tableStructure.sql"));
39         File localData = new File("doc/sampleData.sql");
40         if (localData.exists()) {
41             addFile(stmt, localData);
42         }
43         stmt.executeBatch();
44         stmt.close();
45     }
46
47     private static void addFile(Statement stmt, File f) throws IOException, SQLException {
48         String sql = readFile(f);
49         String[] stmts = sql.split(";");
50         for (String string : stmts) {
51             if ( !string.trim().equals("")) {
52                 stmt.addBatch(string);
53             }
54         }
55     }
56 }