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