论坛首页 Java企业应用论坛

hsql listener

浏览 1476 次
锁定老帖子 主题:hsql listener
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-07-26  

java 代码

/* 文档密级:秘密 */
package com.cpic.b2b.common.web.listener;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;
import org.hsqldb.Server;
import com.cpic.b2b.common.util.StringUtils;

public class HsqlDBlistener implements ServletContextListener {
	
	protected Logger logger = Logger.getLogger(getClass());

	private Server server=new Server();
	private  String path;
	private  String dbName;
	private  int port=-1;
    public void contextInitialized(ServletContextEvent sce) {
        logger.info(" ============= HsqlListener initialize...");
        getInitParam(sce);
        // 启动数据库
        startServer();
    }


    /**
     * 得到数据库路径
     * @param sce
     * @return
     */
    private String getDbPath(ServletContextEvent sce) {
        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() {
    	getServer();
        server.start();
        logger.info(" ============= hsqldb started...");
        // 等待Server启动
        try {
            Thread.sleep(800);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 停止服务
     */
    private void stopServer() {
    	getServer();
    	server.stop();
    	logger.info(" ============= hsqldb stopped...");
    	// 等待Server关闭
    	try {
    		Thread.sleep(800);
    	} catch (InterruptedException e) {
    		e.printStackTrace();
    	}
    }
    
    
    /**
     * 得到服务
     * @param dbPath
     * @param dbName
     * @param port
     */
    private void getServer() {
    	server.setDatabaseName(0, dbName);
    	server.setDatabasePath(0, path + dbName);
    	if (port != -1)
    		server.setPort(port);
    	server.setSilent(true);
    	server.setTrace(true);
    }
    
    /**
     * 得到初始化的参数
     * @param sce
     */
    private void getInitParam(ServletContextEvent sce) {
    	//得到路径
    	getDPath(sce);
    	//得到数据库名称
        getDName(sce);
        // 数据库访问端口
        getDPort(sce);
    }


	private int getDPort(ServletContextEvent sce) {
        try {
            port = Integer.parseInt(sce.getServletContext().getInitParameter("hsql.port"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return port;
	}


	/**
	 * 获取数据库名称
	 * @param sce
	 */
	private String getDName(ServletContextEvent sce) {
		// 数据库文件名
        dbName = sce.getServletContext().getInitParameter("hsql.dbName");
        if (StringUtils.isEmpty(dbName)) {
            logger.info(" ============= Can't get hsqldb.dbName from web.xml Context Param");
            return "";
        }
        return dbName;
	}


	/**
	 * 获取路径
	 * @param sce
	 * @return
	 */
	private String getDPath(ServletContextEvent sce) {
		// 获得数据库文件访问路径
        path = getDbPath(sce);
        if (!path.endsWith("/"))
            path = path + "/";
        if (StringUtils.isEmpty(path)) {
            logger.info(" ============= Can't get hsqldb.path from web.xml Context Param");
            logger.debug("hsqldb_path:" + path);
            return "";
        }
		return path;
	}
    


    public void contextDestroyed(ServletContextEvent sce) {
        logger.info(" ============= HsqlListener destroyed...");
        getInitParam(sce);
        Connection conn = null;
        try {
            Class.forName("org.hsqldb.jdbcDriver");
            conn = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost:"+port+"/"+dbName+"", "sa", "");
            Statement stmt = conn.createStatement();
            stmt.executeUpdate("SHUTDOWN;");
            logger.info(" ============= hsqldb shutdown...");
        } catch (Exception e) {
            e.printStackTrace();
        }
        stopServer();
    }


}




web.xml

 
	<context-param>
        <param-name>hsql.dbPath</param-name>
        <param-value>{webapp.root}/WEB-INF/dbms/db</param-value>
    </context-param>
    <context-param>
        <param-name>hsql.dbName</param-name>
        <param-value>message</param-value>
    </context-param>
    <context-param>
        <param-name>hsql.port</param-name>
        <param-value>9898</param-value>
	</context-param>
	<listener>
		<listener-class>com.cpic.b2b.common.web.listener.HsqlDBlistener</listener-class>
	</listener>


spring 数据库配置

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}"/>
		<property name="url" value="${jdbc.url}">
		</property>
		<property name="username" value="${jdbc.username}"></property>
		<property name="password" value="${jdbc.password}"></property>


jdbc.properties
jdbc.driverClassName=org.hsqldb.jdbcDriver
#jdbc.url=jdbc:hsqldb:hsql:src/DB/message;shutdown=true
jdbc.url=jdbc:hsqldb:hsql://localhost:9898/message
#jdbc.url=jdbc:hsqldb:res:/DB/message
jdbc.username=sa
jdbc.password=

</bean>
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics