1 package org.apache.turbine.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 import org.hsqldb.jdbcDriver;
31
32 public class HsqlDB
33 {
34 private Connection connection = null;
35 private static Log log = LogFactory.getLog(HsqlDB.class);
36
37 public HsqlDB(String uri, String loadFile)
38 throws Exception
39 {
40 Class.forName(jdbcDriver.class.getName());
41
42 this.connection = DriverManager.getConnection(uri, "sa", "");
43
44 if (StringUtils.isNotEmpty(loadFile))
45 {
46 loadSqlFile(loadFile);
47 }
48 }
49
50 public Connection getConnection()
51 {
52 return connection;
53 }
54
55 public void close()
56 {
57 try
58 {
59 connection.close();
60 }
61 catch (Exception e)
62 {
63 }
64 }
65
66 private void loadSqlFile(String fileName)
67 throws Exception
68 {
69 Statement statement = null;
70 try
71 {
72 statement = connection.createStatement();
73 String commands = getFileContents(fileName);
74
75 for (int targetPos = commands.indexOf(';'); targetPos > -1; targetPos = commands.indexOf(';'))
76 {
77 String cmd = commands.substring(0, targetPos + 1);
78 try
79 {
80 statement.execute(cmd);
81 }
82 catch (SQLException sqle)
83 {
84 log.warn("Statement: " + cmd + ": " + sqle.getMessage());
85 }
86
87 commands = commands.substring(targetPos + 2);
88 }
89 }
90 finally
91 {
92 if (statement != null)
93 {
94 statement.close();
95 }
96 }
97 }
98
99 private String getFileContents(String fileName)
100 throws Exception
101 {
102 FileReader fr = new FileReader(fileName);
103
104 char fileBuf[] = new char[1024];
105 StringBuffer sb = new StringBuffer(1000);
106 int res = -1;
107
108 while ((res = fr.read(fileBuf, 0, 1024)) > -1)
109 {
110 sb.append(fileBuf, 0, res);
111 }
112 fr.close();
113 return sb.toString();
114 }
115 }
116