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