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
68 private void loadSqlFile(String fileName)
69 throws Exception
70 {
71 Statement statement = null;
72 try
73 {
74 statement = connection.createStatement();
75 String commands = getFileContents(fileName);
76
77 for (int targetPos = commands.indexOf(';'); targetPos > -1; targetPos = commands.indexOf(';'))
78 {
79 String cmd = commands.substring(0, targetPos + 1).trim();
80
81 if (cmd.startsWith("--"))
82 {
83
84 int lineend = commands.indexOf('\n');
85 if (lineend > -1)
86 {
87 targetPos = lineend - 1;
88 }
89 }
90 else
91 {
92 try
93 {
94 statement.execute(cmd);
95 }
96 catch (SQLException sqle)
97 {
98 log.warn("Statement: " + cmd + ": " + sqle.getMessage());
99 }
100 }
101
102 commands = commands.substring(targetPos + 2);
103 }
104 }
105 finally
106 {
107 if (statement != null)
108 {
109 statement.close();
110 }
111 }
112 }
113
114 private String getFileContents(String fileName)
115 throws Exception
116 {
117 FileReader fr = new FileReader(fileName);
118
119 char fileBuf[] = new char[1024];
120 StringBuffer sb = new StringBuffer(1000);
121 int res = -1;
122
123 while ((res = fr.read(fileBuf, 0, 1024)) > -1)
124 {
125 sb.append(fileBuf, 0, res);
126 }
127 fr.close();
128 return sb.toString();
129 }
130 }
131