/* * Copyright 2004-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.compass.sample.petclinic; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import javax.sql.DataSource; import org.springframework.beans.factory.InitializingBean; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.jdbc.core.JdbcTemplate; /** * @author kimchy */ public class SetUpDatabase implements InitializingBean { private DataSource dataSource; public void afterPropertiesSet() throws Exception { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); String basedir = System.getProperty("basedir"); if (basedir == null) { basedir = ""; } else { basedir += "/"; } String drop = readFile(basedir + "db/hsqldb/dropDB.txt"); try { jdbcTemplate.execute(drop); } catch (Exception e) { // ignore this one } String insert = readFile(basedir + "db/hsqldb/initDB.txt"); jdbcTemplate.execute(insert); String data = readFile(basedir + "db/populateDB.txt"); jdbcTemplate.execute(data); } private String readFile(String filePath) throws DataAccessException { try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath))); StringBuffer sb = new StringBuffer(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } return sb.toString(); } catch (IOException e) { throw new DataAccessResourceFailureException("Failed to read file [" + filePath + "]", e); } } public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } }