import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hsqldb.Server;
/**
* 该类的职责是在WebApp启动时自动开启HSQL服务. 依然使用Server方式,不受AppServer的影响.
*
* @author frank
* @author calvin
*/
public class HsqlListener implements ServletContextListener {
protected Logger logger = Logger.getLogger(getClass());
/*
* (非 Javadoc)
*
* @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent sce) {
logger.info(" ============= HsqlListener initialize...");
// 获得数据库文件访问路径
String path = getDbPath(sce);
if (!path.endsWith("/"))
path = path + "/";
if (StringUtils.isEmpty(path)) {
logger.info(" ============= Can't get hsqldb.path from web.xml Context Param");
return;
}
logger.debug("hsqldb_path:" + path);
// 数据库文件名
String dbName = sce.getServletContext().getInitParameter("hsql.dbName");
if (StringUtils.isEmpty(dbName)) {
logger.info(" ============= Can't get hsqldb.dbName from web.xml Context Param");
return;
}
// 数据库访问端口
int port = -1;
try {
port = Integer.parseInt(sce.getServletContext().getInitParameter("hsql.port"));
} catch (Exception e) {
e.printStackTrace();
return;
}
// 启动数据库
startServer(path, dbName, port);
}
/**
* 获得数据库文件访问路径
*
* @param sce
* @return
*/
private String getDbPath(ServletContextEvent sce) {
String path = sce.getServletContext().getInitParameter("hsql.dbPath");
if (path.startsWith("{user.home}")) {
path = path.replaceFirst("\\{user.home\\}", System.getProperty("user.home").replace('\\', '/'));
}
if (path.startsWith("{webapp.root}")) {
path = path.replaceFirst("\\{webapp.root\\}", sce.getServletContext().getRealPath("/").replace('\\', '/'));
}
return path;
}
/**
* 启动数据库
*
* @param dbPath
* @param dbName
* @param port
*/
private void startServer(String dbPath, String dbName, int port) {
Server server = new Server();
server.setDatabaseName(0, dbName);
server.setDatabasePath(0, dbPath + dbName);
if (port != -1)
server.setPort(port);
server.setSilent(true);
server.setTrace(true);
server.start();
logger.info(" ============= hsqldb started...");
// 等待Server启动
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/*
* (非 Javadoc)
*
* @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent sce) {
logger.info(" ============= HsqlListener destroyed...");
Connection conn = null;
try {
Class.forName("org.hsqldb.jdbcDriver");
conn = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost:9002/weed", "sa", "sa");
Statement stmt = conn.createStatement();
stmt.executeUpdate("SHUTDOWN;");
logger.info(" ============= hsqldb shutdown...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
|