1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.configuration2.test;
19
20 import java.io.FileReader;
21 import java.sql.Connection;
22 import java.sql.DriverManager;
23 import java.sql.SQLException;
24 import java.sql.Statement;
25
26 import org.apache.commons.lang3.StringUtils;
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29
30
31
32
33
34 public class HsqlDB {
35 private static final Log log = LogFactory.getLog(HsqlDB.class);
36 private final Connection connection;
37
38 public HsqlDB(final String uri, final String databaseDriver, final String loadFile) throws Exception {
39 Class.forName(databaseDriver);
40
41 this.connection = DriverManager.getConnection(uri, "sa", "");
42
43 if (StringUtils.isNotEmpty(loadFile)) {
44 loadSqlFile(loadFile);
45 }
46 this.connection.commit();
47 }
48
49 public void close() {
50 try {
51 connection.close();
52 } catch (final Exception e) {
53 }
54 }
55
56 public Connection getConnection() {
57 return connection;
58 }
59
60 private String getFileContents(final String fileName) throws Exception {
61 try (FileReader fr = new FileReader(fileName)) {
62
63 final char[] fileBuf = new char[1024];
64 final StringBuilder sb = new StringBuilder(1000);
65 int res = -1;
66
67 while ((res = fr.read(fileBuf, 0, 1024)) > -1) {
68 sb.append(fileBuf, 0, res);
69 }
70 return sb.toString();
71 }
72 }
73
74 private void loadSqlFile(final String fileName) throws Exception {
75 try (Statement statement = connection.createStatement()) {
76 String commands = getFileContents(fileName);
77
78 for (int targetPos = commands.indexOf(';'); targetPos > -1; targetPos = commands.indexOf(';')) {
79 final String cmd = commands.substring(0, targetPos + 1);
80 try {
81 statement.execute(cmd);
82 } catch (final SQLException sqle) {
83 log.warn("Statement: " + cmd + ": " + sqle.getMessage());
84 }
85
86 commands = commands.substring(targetPos + 2);
87 }
88 }
89 }
90 }