01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (http://h2database.com/html/license.html).
04: * Initial Developer: H2 Group
05: */
06: package org.h2.server.web;
07:
08: import java.sql.Connection;
09: import java.sql.DriverManager;
10:
11: import javax.servlet.ServletContext;
12: import javax.servlet.ServletContextEvent;
13: import javax.servlet.ServletContextListener;
14:
15: import org.h2.tools.Server;
16: import org.h2.util.StringUtils;
17:
18: /**
19: * This class can be used to start the H2 TCP server (or other H2 servers, for
20: * example the PG server) inside a web application container such as Tomcat or
21: * Jetty. It can also open a database connection.
22: */
23: public class DbStarter implements ServletContextListener {
24:
25: private Connection conn;
26: private Server server;
27:
28: public void contextInitialized(
29: ServletContextEvent servletContextEvent) {
30: try {
31: org.h2.Driver.load();
32:
33: // This will get the setting from a context-param in web.xml if defined:
34: ServletContext servletContext = servletContextEvent
35: .getServletContext();
36: String url = getParameter(servletContext, "db.url",
37: "jdbc:h2:~/test");
38: String user = getParameter(servletContext, "db.user", "sa");
39: String password = getParameter(servletContext,
40: "db.password", "sa");
41:
42: conn = DriverManager.getConnection(url, user, password);
43: servletContext.setAttribute("connection", conn);
44:
45: // Start the server if configured to do so
46: String serverParams = getParameter(servletContext,
47: "db.tcpServer", null);
48: if (serverParams != null) {
49: String[] params = StringUtils.arraySplit(serverParams,
50: ' ', true);
51: server = Server.createTcpServer(params);
52: server.start();
53: }
54: // To access the database using the server, use the URL:
55: // jdbc:h2:tcp://localhost/~/test
56:
57: } catch (Exception e) {
58: e.printStackTrace();
59: }
60: }
61:
62: private String getParameter(ServletContext servletContext,
63: String key, String defaultValue) {
64: String value = servletContext.getInitParameter(key);
65: return value == null ? defaultValue : value;
66: }
67:
68: public Connection getConnection() {
69: return conn;
70: }
71:
72: public void contextDestroyed(ServletContextEvent servletContextEvent) {
73: if (server != null) {
74: server.stop();
75: server = null;
76: }
77: try {
78: conn.close();
79: } catch (Exception e) {
80: e.printStackTrace();
81: }
82: }
83: }
|