1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.syncope.fit.buildtools;
20
21 import java.nio.charset.StandardCharsets;
22 import java.sql.SQLException;
23 import java.util.Objects;
24 import javax.servlet.ServletContext;
25 import javax.servlet.ServletContextEvent;
26 import javax.servlet.ServletContextListener;
27 import javax.servlet.annotation.WebListener;
28 import javax.sql.DataSource;
29 import org.h2.tools.Server;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import org.springframework.jdbc.datasource.init.DataSourceInitializer;
33 import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
34 import org.springframework.web.context.WebApplicationContext;
35 import org.springframework.web.context.support.WebApplicationContextUtils;
36
37
38
39
40 @WebListener
41 public class H2StartStopListener implements ServletContextListener {
42
43 private static final Logger LOG = LoggerFactory.getLogger(H2StartStopListener.class);
44
45 private static final String H2_TESTDB = "h2TestDb";
46
47 @Override
48 public void contextInitialized(final ServletContextEvent sce) {
49 ServletContext context = sce.getServletContext();
50 WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
51
52 try {
53 Server h2TestDb = new Server();
54 h2TestDb.runTool("-ifNotExists", "-tcp", "-tcpDaemon", "-web", "-webDaemon",
55 "-webPort", Objects.requireNonNull(ctx).getEnvironment().getProperty("testdb.webport"));
56
57 context.setAttribute(H2_TESTDB, h2TestDb);
58 } catch (SQLException e) {
59 LOG.error("Could not start H2 test db", e);
60 }
61
62 DataSource datasource = ctx.getBean("testDataSource", DataSource.class);
63
64 try {
65 ResourceDatabasePopulator populator =
66 new ResourceDatabasePopulator(ctx.getResource("classpath:/testdb.sql"));
67 populator.setSqlScriptEncoding(StandardCharsets.UTF_8.name());
68 DataSourceInitializer init = new DataSourceInitializer();
69 init.setDataSource(datasource);
70 init.setEnabled(true);
71 init.setDatabasePopulator(populator);
72 init.afterPropertiesSet();
73 LOG.info("H2 database successfully initialized");
74 } catch (Exception e) {
75 LOG.error("Could not initialize H2", e);
76 }
77 }
78
79 @Override
80 public void contextDestroyed(final ServletContextEvent sce) {
81 Server h2TestDb = (Server) sce.getServletContext().getAttribute(H2_TESTDB);
82 if (h2TestDb != null) {
83 h2TestDb.shutdown();
84 }
85 }
86 }