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