Skip to content

Instantly share code, notes, and snippets.

@lviggiano
Created May 18, 2012 20:26
Show Gist options
  • Save lviggiano/2727424 to your computer and use it in GitHub Desktop.
Save lviggiano/2727424 to your computer and use it in GitHub Desktop.
ServletContextListener that Sets up the database schema after first creation; and sample web.xml usage.
// DbStarter class: take it from https://gist.github.com/2727189
import static com.foo.bar.DbStarter.ctx;
import static com.foo.bar.DbStarter.getConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class DbSetupScript implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
try {
Connection conn = getConnection();
try {
if (isEmpty(conn)) {
create(conn, ctx(sce));
}
} finally {
conn.close();
}
} catch (SQLException e) {
ctx(sce).log("Exception during database creation", e);
}
}
protected boolean isEmpty(Connection conn) throws SQLException {
PreparedStatement stmt = conn.prepareStatement("show tables");
try {
ResultSet rs = stmt.executeQuery();
try {
return ! rs.next();
} finally {
rs.close();
}
} finally {
stmt.close();
}
}
protected int create(Connection conn, ServletContext ctx) throws SQLException {
String script = ctx.getInitParameter("db.setup.script");
if (script == null)
return usage(ctx);
ctx.log("Running script from '" + script + "'.");
int count = runScript(conn, script);
ctx.log("Executed " + count + " queries.");
return count;
}
protected int runScript(Connection conn, String script)
throws SQLException {
String sql = "runscript from '" + script +"'";
PreparedStatement stmt = conn.prepareStatement(sql);
try {
return stmt.executeUpdate();
} finally {
stmt.close();
}
}
protected int usage(ServletContext ctx) {
ctx.log("Please specify context-param 'db.setup.script' in your web.xml.");
ctx.log("Example:");
ctx.log(" <context-param>");
ctx.log(" <param-name>db.setup.script</param-name>");
ctx.log(" <param-value>classpath:com/foo/bar/schema.sql</param-value>");
ctx.log(" </context-param>");
return -1;
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5" xmlns="http://java.sun.com/xml/ns/javaee">
...
<context-param>
<param-name>db.setup.script</param-name>
<param-value>classpath:com/foo/bar/schema.sql</param-value>
</context-param>
<listener>
<listener-class>com.foo.bar.DbSetupScript</listener-class>
</listener>
...
</web-app>
@lviggiano
Copy link
Author

use freely.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment