1 package org.apache.commons.configuration.test;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 import java.io.FileReader;
20
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.lang.StringUtils;
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29
30 /***
31 * Stolen from Turbine
32 *
33 * @author <a href="mailto:hps@intermeta.de">Henning P. Schmiedehausen</a>
34 * @version $Id: HsqlDB.java 155408 2005-02-26 12:56:39Z dirkv $
35 */
36
37 public class HsqlDB
38 {
39 private Connection connection = null;
40 private static Log log = LogFactory.getLog(HsqlDB.class);
41
42 public HsqlDB(String uri, String databaseDriver, String loadFile)
43 throws Exception
44 {
45 Class.forName(databaseDriver);
46
47 this.connection = DriverManager.getConnection(uri, "sa", "");
48
49 if (StringUtils.isNotEmpty(loadFile))
50 {
51 loadSqlFile(loadFile);
52 }
53 this.connection.commit();
54 }
55
56 public Connection getConnection()
57 {
58 return connection;
59 }
60
61 public void close()
62 {
63 try
64 {
65 connection.close();
66 }
67 catch (Exception e)
68 {
69 }
70 }
71
72 private void loadSqlFile(String fileName)
73 throws Exception
74 {
75 Statement statement = null;
76 try
77 {
78 statement = connection.createStatement();
79 String commands = getFileContents(fileName);
80
81 for (int targetPos = commands.indexOf(';'); targetPos > -1; targetPos = commands.indexOf(';'))
82 {
83 String cmd = commands.substring(0, targetPos + 1);
84 try
85 {
86 statement.execute(cmd);
87 }
88 catch (SQLException sqle)
89 {
90 log.warn("Statement: " + cmd + ": " + sqle.getMessage());
91 }
92
93 commands = commands.substring(targetPos + 2);
94 }
95 }
96 finally
97 {
98 if (statement != null)
99 {
100 statement.close();
101 }
102 }
103 }
104
105 private String getFileContents(String fileName)
106 throws Exception
107 {
108 FileReader fr = new FileReader(fileName);
109
110 char fileBuf[] = new char[1024];
111 StringBuffer sb = new StringBuffer(1000);
112 int res = -1;
113
114 while ((res = fr.read(fileBuf, 0, 1024)) > -1)
115 {
116 sb.append(fileBuf, 0, res);
117 }
118 fr.close();
119 return sb.toString();
120 }
121 }
122