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