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