1 package org.apache.fulcrum.security.torque;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.File;
23 import java.io.FileInputStream;
24 import java.io.InputStream;
25 import java.sql.Connection;
26 import java.sql.DriverManager;
27 import java.sql.Statement;
28 import java.util.ArrayList;
29 import java.util.List;
30 import java.util.Scanner;
31
32 import org.apache.commons.lang3.StringUtils;
33 import org.hsqldb.jdbcDriver;
34
35
36
37
38
39
40
41
42
43 public class HsqlDB {
44 private Connection connection = null;
45 private static String URI = "jdbc:hsqldb:.";
46
47 public HsqlDB(String loadFile) throws Exception {
48 Class.forName(jdbcDriver.class.getName());
49 this.connection = DriverManager.getConnection(URI, "SA", "");
50 if (StringUtils.isNotEmpty(loadFile)) {
51 loadSqlFile(loadFile);
52 }
53 }
54
55 public HsqlDB(File loadFile) throws Exception {
56 this(loadFile.getAbsolutePath());
57 }
58
59 public Connection getConnection() {
60 return connection;
61 }
62
63 public void close() {
64 try {
65 connection.close();
66 } catch (Exception e) {
67 }
68 }
69
70
71
72
73 private void loadSqlFile(String fileName) throws Exception {
74 Statement statement = null;
75 try {
76 statement = connection.createStatement();
77
78 List<String> commands = getFileContents(fileName);
79 for (String cmd : commands)
80 statement.executeUpdate(cmd);
81
82 } finally {
83 if (statement != null) {
84 statement.close();
85 }
86 }
87 }
88
89 private List<String> getFileContents(String fileName) throws Exception {
90
91 StringBuilder sb = new StringBuilder(1000);
92 Scanner s = null;
93 try {
94 InputStream is = new FileInputStream(new File(fileName));
95 s = new Scanner(is);
96 s.useDelimiter("(\r?\n)");
97
98 boolean inComment = false;
99 while (s.hasNext()) {
100 String line = s.next();
101
102 if (inComment == true) {
103 if (line.endsWith("*/"))
104 inComment = false;
105 } else {
106
107 if (!line.startsWith("--")) {
108 if (line.trim().length() > 0) {
109 sb.append(line);
110 }
111 }
112 }
113 }
114 } finally {
115 if (s != null)
116 s.close();
117 }
118
119 String sql = sb.toString();
120 sb = new StringBuilder();
121 String[] commands = sql.split(";");
122 List<String> sqlCmds = new ArrayList<>();
123 for (String cmd : commands)
124 sqlCmds.add(cmd + ";\n");
125
126 return sqlCmds;
127 }
128
129 public void addSQL(String sqlFile) throws Exception {
130 if (StringUtils.isNotEmpty(sqlFile)) {
131 loadSqlFile(sqlFile);
132 }
133 }
134
135 public void addSQL(File sqlFile) throws Exception {
136 this.addSQL(sqlFile.getAbsolutePath());
137 }
138 }