1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jdiagnose.library.db;
17
18 import java.io.BufferedReader;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.InputStreamReader;
22 import java.sql.Connection;
23 import java.sql.ResultSet;
24 import java.sql.SQLException;
25 import java.sql.Statement;
26
27 import javax.sql.DataSource;
28
29 import org.springframework.core.io.DefaultResourceLoader;
30 import org.springframework.core.io.Resource;
31 import org.springframework.core.io.ResourceLoader;
32
33 /***
34 * User: jamie
35 * Date: May 30, 2004
36 * Time: 7:42:52 PM
37 */
38 public class DatabaseInit {
39
40 private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory
41 .getLog(DatabaseInit.class);
42
43 private DataSource dataSource = null;
44
45 private String sql;
46
47 private ResourceLoader resourceLoader = new DefaultResourceLoader();
48
49 public void init() throws SQLException, IOException {
50 log.debug("initialising database");
51 Connection connection = null;
52 try {
53 connection = dataSource.getConnection();
54 ResultSet tables = connection.getMetaData().getTables(null, null, "DIAGNOSTICRESULT", new String[] {"TABLE"});
55 if(!tables.next()) {
56 Statement statement = connection.createStatement();
57 Resource resource = resourceLoader.getResource(sql);
58 InputStream in = resource.getInputStream();
59 BufferedReader reader = new BufferedReader(new InputStreamReader(in));
60 StringBuffer ddl = new StringBuffer();
61 String line = null;
62 while((line = reader.readLine()) != null) {
63 ddl.append(line);
64 }
65 log.debug("got sql: " + ddl);
66 statement.execute(ddl.toString());
67 connection.commit();
68 }
69 } finally {
70 if(connection != null) {
71 connection.close();
72 }
73 }
74 log.debug("finished initialising database");
75 }
76
77 /***
78 * @return Returns the resourceLoader.
79 */
80 public ResourceLoader getResourceLoader() {
81 return resourceLoader;
82 }
83 /***
84 * @param resourceLoader The resourceLoader to set.
85 */
86 public void setResourceLoader(ResourceLoader resourceLoader) {
87 this.resourceLoader = resourceLoader;
88 }
89 /***
90 * @return Returns the sql.
91 */
92 public String getSql() {
93 return sql;
94 }
95 /***
96 * @param sql The sql to set.
97 */
98 public void setSql(String sql) {
99 this.sql = sql;
100 }
101 /***
102 * @return Returns the dataSource.
103 */
104 public DataSource getDataSource() {
105 return dataSource;
106 }
107 /***
108 * @param dataSource The dataSource to set.
109 */
110 public void setDataSource(DataSource dataSource) {
111 this.dataSource = dataSource;
112 }
113 }