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