File D:\maven-qcr-plugin-testsunitaires\qcr4java\h2-1.3.170-sources\target\site\qc\lecode\server\web\DbStarter.java.html

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