01: /*
02: * Copyright 2004-2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package org.compass.sample.petclinic;
18:
19: import java.io.BufferedReader;
20: import java.io.FileInputStream;
21: import java.io.IOException;
22: import java.io.InputStreamReader;
23:
24: import javax.sql.DataSource;
25:
26: import org.springframework.beans.factory.InitializingBean;
27: import org.springframework.dao.DataAccessException;
28: import org.springframework.dao.DataAccessResourceFailureException;
29: import org.springframework.jdbc.core.JdbcTemplate;
30:
31: /**
32: * @author kimchy
33: */
34: public class SetUpDatabase implements InitializingBean {
35:
36: private DataSource dataSource;
37:
38: public void afterPropertiesSet() throws Exception {
39: JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
40:
41: String basedir = System.getProperty("basedir");
42: if (basedir == null) {
43: basedir = "";
44: } else {
45: basedir += "/";
46: }
47: String drop = readFile(basedir + "db/hsqldb/dropDB.txt");
48: try {
49: jdbcTemplate.execute(drop);
50: } catch (Exception e) {
51: // ignore this one
52: }
53: String insert = readFile(basedir + "db/hsqldb/initDB.txt");
54: jdbcTemplate.execute(insert);
55: String data = readFile(basedir + "db/populateDB.txt");
56: jdbcTemplate.execute(data);
57: }
58:
59: private String readFile(String filePath) throws DataAccessException {
60: try {
61: BufferedReader reader = new BufferedReader(
62: new InputStreamReader(new FileInputStream(filePath)));
63: StringBuffer sb = new StringBuffer();
64: String line = null;
65: while ((line = reader.readLine()) != null) {
66: sb.append(line);
67: }
68: return sb.toString();
69: } catch (IOException e) {
70: throw new DataAccessResourceFailureException(
71: "Failed to read file [" + filePath + "]", e);
72: }
73: }
74:
75: public DataSource getDataSource() {
76: return dataSource;
77: }
78:
79: public void setDataSource(DataSource dataSource) {
80: this.dataSource = dataSource;
81: }
82: }
|