package jp.sf.amateras.mirage.example.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.commons.io.IOUtils;

public class InitializeDatabaseServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	public void init() throws ServletException {
		super.init();
		try {
			System.out.println("Initializing database...");
			
			Class.forName("org.h2.Driver");
			Connection conn = DriverManager.getConnection(
					"jdbc:h2:mem:mydb;DB_CLOSE_DELAY=-1", "sa", "");
			
			Statement stmt = conn.createStatement();
			
			String sql = IOUtils.toString(
					InitializeDatabaseServlet.class.getResourceAsStream("/create.sql"));
			stmt.executeUpdate(sql);
			
			stmt.close();
			conn.close();
			
			System.out.println("Database has been initialized!");
			
		} catch(Exception ex){
			throw new ServletException(ex);
		}
	}
	
}
