This project has retired. For details please refer to its
Attic page.
InitContextListener xref
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.apache.tiles.test.init;
23
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.sql.Connection;
27 import java.sql.SQLException;
28 import java.sql.Statement;
29
30 import javax.servlet.ServletContextEvent;
31 import javax.servlet.ServletContextListener;
32 import javax.sql.DataSource;
33
34 import org.apache.commons.io.IOUtils;
35 import org.apache.tiles.test.exception.TilesTestRuntimeException;
36 import org.hsqldb.jdbc.jdbcDataSource;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40
41
42
43
44
45 public class InitContextListener implements ServletContextListener {
46
47
48
49
50 private final Logger log = LoggerFactory
51 .getLogger(InitContextListener.class);
52
53
54 public void contextInitialized(ServletContextEvent event) {
55 DataSource dataSource = createDataSource();
56 event.getServletContext().setAttribute("dataSource", dataSource);
57 String[] commands = getSQLCommands();
58 executeCommands(dataSource, commands);
59 }
60
61
62 public void contextDestroyed(ServletContextEvent event) {
63
64 }
65
66
67
68
69
70
71 private DataSource createDataSource() {
72 jdbcDataSource dataSource = new jdbcDataSource();
73 dataSource.setDatabase("jdbc:hsqldb:mem:tiles");
74 dataSource.setUser("sa");
75 dataSource.setPassword("");
76 return dataSource;
77 }
78
79
80
81
82
83
84 private String[] getSQLCommands() {
85 InputStream stream = getClass().getResourceAsStream(
86 "/org/apache/tiles/test/db/schema.sql");
87 String text;
88 try {
89 text = IOUtils.toString(stream);
90 } catch (IOException e) {
91 throw new TilesTestRuntimeException("Cannot read schema SQL text", e);
92 } finally {
93 try {
94 stream.close();
95 } catch (IOException e) {
96 log.error("Error during close of the stream containing the SQL schema", e);
97 }
98 }
99 return text.split(";");
100 }
101
102
103
104
105
106
107
108 private void executeCommands(DataSource dataSource, String[] commands) {
109 Connection conn = null;
110 Statement stmt = null;
111 try {
112 conn = dataSource.getConnection();
113 for (int i = 0; i < commands.length; i++) {
114 stmt = conn.createStatement();
115 stmt.executeUpdate(commands[i]);
116 }
117 conn.commit();
118 } catch (SQLException e) {
119 try {
120 conn.rollback();
121 } catch (SQLException e1) {
122 log.error("Error during rollback", e);
123 }
124 throw new TilesTestRuntimeException("Error during execution of SQL commands", e);
125 } finally {
126 try {
127 if (conn != null) {
128 conn.close();
129 }
130 if (stmt != null) {
131 stmt.close();
132 }
133 } catch (SQLException e) {
134 log.error("Error during closing resources", e);
135 }
136 }
137 }
138 }