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.nio.charset.Charset;
21 import java.nio.file.Paths;
22 import java.sql.Connection;
23 import java.sql.DriverManager;
24 import java.sql.SQLException;
25 import java.sql.Statement;
26
27 import org.apache.commons.io.file.PathUtils;
28 import org.apache.commons.lang3.StringUtils;
29 import org.apache.commons.logging.Log;
30 import org.apache.commons.logging.LogFactory;
31
32
33
34
35 public class HsqlDB {
36
37 private static final Log LOG = LogFactory.getLog(HsqlDB.class);
38
39 private final Connection connection;
40
41 public HsqlDB(final String uri, final String databaseDriver, final String loadFile) throws Exception {
42 Class.forName(databaseDriver);
43 this.connection = DriverManager.getConnection(uri, "sa", "");
44 if (StringUtils.isNotEmpty(loadFile)) {
45 loadSqlFile(loadFile);
46 }
47 this.connection.commit();
48 }
49
50 public void close() {
51 try {
52 connection.close();
53 } catch (final Exception e) {
54 }
55 }
56
57 public Connection getConnection() {
58 return connection;
59 }
60
61 private String getFileContents(final String fileName) throws Exception {
62 return PathUtils.readString(Paths.get(fileName), Charset.defaultCharset());
63 }
64
65 private void loadSqlFile(final String fileName) throws Exception {
66 try (Statement statement = connection.createStatement()) {
67 String commands = getFileContents(fileName);
68 for (int targetPos = commands.indexOf(';'); targetPos > -1; targetPos = commands.indexOf(';')) {
69 final String cmd = commands.substring(0, targetPos + 1);
70 try {
71 statement.execute(cmd);
72 } catch (final SQLException sqle) {
73 LOG.warn("Statement: " + cmd + ": " + sqle.getMessage());
74 }
75 commands = commands.substring(targetPos + 2);
76 }
77 }
78 }
79 }